使用UIImagePicker选择图像后,重新加载UICollectionView的正确时间和位置

问题描述 投票:0回答:2

我在理解我应该在UICollectionView中重新加载数据时遇到一些麻烦,以便从库中通过UIImagePicker选取的图像显示在Collection View上。这是我现在正在使用的代码,但我似乎无法理解为什么它会在选择器被解雇后崩溃给我一个SIGBRT错误。我通过故事板设置代表。

@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重新加载,但仍然没运气。无论何时按下重新加载,当我执行应用程序时因NSException错误而崩溃。我确保在显示图像时数组不为空。有任何想法吗?

swift uicollectionview reloaddata
2个回答
0
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.