首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用UIImagePicker拾取图像后重新加载UICollectionView的正确时间和位置

使用UIImagePicker拾取图像后重新加载UICollectionView的正确时间和位置
EN

Stack Overflow用户
提问于 2019-04-16 20:31:13
回答 2查看 44关注 0票数 0

我很难理解应该在UICollectionView中的什么位置重新加载数据,以便通过UIImagePicker从图库中选取的图像显示在集合视图上。这就是我现在正在使用的代码,但我似乎不明白为什么在选择器被关闭之后,它会崩溃,并给我一个SIGBRT错误。我通过故事板设置了代理。

代码语言:javascript
复制
@IBOutlet weak var addImage: UIButton!
var imagesArray : [UIImage] = []
@IBAction func buttonPickerPressed(_ sender: UIButton) {
    if imagesArray.count < 5 {
    picker.delegate = self
    picker.sourceType = .photoLibrary

    present(picker, animated: true, completion: nil)
    }
    else {
    addImage.isHidden = true }
}
@IBOutlet weak var collectionViewImages: UICollectionView!
let picker = UIImagePickerController()



func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imagesArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "", for: indexPath) as! CollectionViewCell
    cell.imageDisplayed.image = imagesArray[indexPath.row]
    return cell
}


func imagePickerController(_ picker: UIImagePickerController,
                           didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
    collectionViewImages.delegate = self
    if imagesArray.count < 5 {
        guard let selectedImage = info[.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        imagesArray.append(selectedImage) //whatever space is free] = selectedImage
        picker.dismiss(animated: true, completion: nil)
        self.collectionViewImages.reloadData()
    }
    else {
        let alert = UIAlertController(title: "Error", message: "Maximum amount of images reached", preferredStyle: .alert)
        let action = UIAlertAction(title: "Dismiss", style: .default) { (action) in
        return}
        alert.addAction(action)
        picker.dismiss(animated:true ,completion:nil)
        present(alert, animated: true, completion: nil)}

}

- UPDATE -我还在主VC中创建了一个按钮,它有一个动作,当按下按钮时,它会触发collectionView重新加载,但仍然没有成功。无论我在什么时候按下reload,当我这样做的时候,应用程序都会崩溃,并出现NSException错误。我还确保在显示图像时数组不为空。有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2019-04-16 20:46:00

设置collectionViewImages的数据源。并在picker完成处理程序中重新加载collectionViewImages

票数 0
EN

Stack Overflow用户

发布于 2019-04-17 19:51:26

解决了它。显然,问题是我使用idenxPath.row方法来获取索引,而我应该使用indexPath.item来访问图像数组。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55708224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档