[英]Replacing default images in a collection view with user selected photos- swift
So I have a collection view that populates three default images on each cell.所以我有一个集合视图,它在每个单元格上填充三个默认图像。 The user can select images through the new PHPicker, what I want to accomplish is
用户可以通过新的PHPicker来选择图片,我想要完成的是
currently when I send a new photo to the imgArray it gets displayed in a new cell before the camera cell, as I'm using insert method like so: imgArray.insert(image, at: 0).目前,当我将新照片发送到 imgArray 时,它会显示在相机单元之前的新单元格中,因为我正在使用插入方法,如下所示:imgArray.insert(image, at: 0)。
My code:我的代码:
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()
}
}
}
}
}
I have tried to remove the first item of the array, and then insert new photo like this:我试图删除数组的第一项,然后像这样插入新照片:
self.imgArray.removeFirst(1)
self.imgArray.insert(image, at: 0)
self.collectionView.reloadData()
but this would work just one time as the code itself says, after that all replacement takes place just in the first cell.但这只会像代码本身所说的那样工作一次,之后所有替换都发生在第一个单元格中。 So how can I get to other cells after first replacement?
那么在第一次更换后如何才能到达其他单元格呢? Any other approach that gives the same result will help me alot.
任何其他给出相同结果的方法都会对我有很大帮助。 Thanks in advance guys!
在此先感谢各位!
One way to do this is to keep two image arrays, defaultImages
of type [UIImage]
and inputImages
of type [UIImage?]
.这样做的一个办法是保持两个影像阵列,
defaultImages
型[UIImage]
和inputImages
类型[UIImage?]
。 The defaultImages
will hold your camera and photo images, and inputImages
will hold images selected by the user. defaultImages
将保存您的相机和照片图像,而inputImages
将保存用户选择的图像。 Initialize the images as:将图像初始化为:
defaultImages = [UIImage(systemName: "camera"), UIImage(systemName: "photo"), UIImage(systemName: "photo")]
inputImages: [UIImage?] = [nil, nil, nil]
To select the correct photo for index index
use:要为索引
index
选择正确的照片:
image = inputImages[index] ?? defaultImages[index]
To add a user-input image at index index
use:要在索引
index
处添加用户输入图像,请使用:
image: UIImage = ... // Get the image.
inputImages[index] = image
And to delete a user-input image at index index
use:并删除索引
index
处的用户输入图像,请使用:
inputImages[index] = nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.