【发布时间】:2021-12-09 12:07:35
【问题描述】:
所以我有一个集合视图,它在每个单元格上填充三个默认图像。用户可以通过新的PHPicker来选择图片,我想要完成的是
- 用选定的照片替换默认图像,因此第一个选定的图像应该替换相机单元等等......(通过底部的链接查看图像)
- 在用户删除所选图像时显示默认图像
目前,当我将新照片发送到 imgArray 时,它会显示在相机单元之前的新单元中,因为我正在使用如下插入方法:imgArray.insert(image, at: 0)。
我的代码:
var imgArray = [UIImage(systemName: "camera"), UIImage(systemName: "photo"), UIImage(systemName: "photo")]
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "1", for: indexPath) as! CustomCell
cell.imageView.image = imgArray[indexPath.row]
cell.imageView.tintColor = .gray
cell.imageView.layer.cornerRadius = 4
return cell
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
dismiss(animated: true, completion: nil)
for item in results {
item.itemProvider.loadObject(ofClass: UIImage.self) { image, error in
if let image = image as? UIImage {
DispatchQueue.main.async {
self.imgArray.insert(image, at: 0)
self.collectionView.reloadData()
}
}
}
}
}
我试图删除数组的第一项,然后像这样插入新照片:
self.imgArray.removeFirst(1)
self.imgArray.insert(image, at: 0)
self.collectionView.reloadData()
但是正如代码本身所说,这只会工作一次,之后所有替换都只发生在第一个单元格中。 那么第一次更换后如何才能到达其他单元格?任何其他给出相同结果的方法都会对我有很大帮助。提前谢谢各位!
【问题讨论】:
标签: swift uicollectionview uiimagepickercontroller phpickerviewcontroller