我很难理解应该在哪里将数据重新加载到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)}
}
----------更新---------- 我还在主VC中创建了一个按钮,并带有一个动作,以便在按下该按钮时会触发collectionView重新加载,但是仍然没有运气。无论我什么时候按下reload,当我这样做时,应用程序都会因NSException错误而崩溃。我确保显示图像时数组也不为空。有什么想法吗?
答案 0 :(得分:0)
设置collectionViewImages
的数据源。并在collectionViewImages
完成处理程序中重新加载picker
。
答案 1 :(得分:0)
解决了。显然问题是我正在使用idenxPath.row方法来获取索引,而我应该使用indexPath.item来访问图像数组。