我很难理解应该在UICollectionView中的什么位置重新加载数据,以便通过UIImagePicker从图库中选取的图像显示在集合视图上。这就是我现在正在使用的代码,但我似乎不明白为什么在选择器被关闭之后,它会崩溃,并给我一个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重新加载,但仍然没有成功。无论我在什么时候按下reload,当我这样做的时候,应用程序都会崩溃,并出现NSException错误。我还确保在显示图像时数组不为空。有什么想法吗?
发布于 2019-04-16 20:46:00
设置collectionViewImages的数据源。并在picker完成处理程序中重新加载collectionViewImages。
发布于 2019-04-17 19:51:26
解决了它。显然,问题是我使用idenxPath.row方法来获取索引,而我应该使用indexPath.item来访问图像数组。
https://stackoverflow.com/questions/55708224
复制相似问题