因此,我有一个集合视图,它在每个单元格上填充三个默认图像。用户可以通过新的PHPicker选择图像,我想要完成的是
目前,当我向imgArray发送一张新照片时,它会显示在相机单元格之前的一个新单元格中,因为我使用的插入方法如下:imgArray.insert(图像,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()但是,就像代码本身说的那样,这只起了一次作用,然后所有的替换都发生在第一个单元格中。那么,在第一次替换之后,我怎样才能到达其他的细胞呢?任何其他给出同样结果的方法都会对我有很大帮助。谢谢,伙计们!
发布于 2021-10-30 18:34:54
一种方法是保留两个图像数组,defaultImages类型为[UIImage],inputImages类型为[UIImage?]。defaultImages将保存您的相机和照片图像,而inputImages将保存用户选择的图像。将图像初始化为:
defaultImages = [UIImage(systemName: "camera"), UIImage(systemName: "photo"), UIImage(systemName: "photo")]
inputImages: [UIImage?] = [nil, nil, nil]若要为索引index选择正确的照片,请使用:
image = inputImages[index] ?? defaultImages[index]若要在索引index中添加用户输入图像,请使用:
image: UIImage = ... // Get the image.
inputImages[index] = image若要删除索引index上的用户输入图像,请使用:
inputImages[index] = nilhttps://stackoverflow.com/questions/69683774
复制相似问题