gpt4 book ai didi

ios - 选择该单元格时如何将图像从照片库上传到特定的 Collection View 单元格?

转载 作者:行者123 更新时间:2023-11-28 07:35:05 26 4
gpt4 key购买 nike

我希望能够允许用户在选择图片时将图片从照片库上传到 collectionview 中的特定单元格。我这里有两个问题。

(1) 我不确定我是否正确调用了 cellTapped() 函数。

(2) 我希望能够使用标签来存储 indexpath.row 但不确定如何在 imagepickercontroller 函数中调用标签。感谢帮助。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let cell: UICollectionViewCell = collectionView.cellForItem(at: indexPath)!
cell.layer.borderWidth = 4.0
cell.layer.borderColor = UIColor.blue.cgColor
cellTapped()

}


func cellTapped(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}


func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
dismiss(animated: true, completion: nil)
}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

guard let selectedImage = info[.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
dismiss(animated: true, completion: nil)
collectionView?.reloadData()
}

最佳答案

您需要记住在选择图像之前点击了哪个单元格。您可以将索引保存在 collectionView(_:, didSelectItemAt:)

// instance property
private var selectedCellIndexPath: IndexPath?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

selectedCellIndexPath = indexPath
let cell: UICollectionViewCell = collectionView.cellForItem(at: indexPath)!
cell.layer.borderWidth = 4.0
cell.layer.borderColor = UIColor.blue.cgColor
cellTapped()

}

然后您需要在选择图像并重新加载集合时更新数据源。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

guard let selectedImage = info[.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
dismiss(animated: true, completion: nil)

// let us assume that your collection relies on some array called 'images'
guard let selectedCellIndexPath = selectedCellIndexPath,
selectedCellIndexPath.item < images.count else {
return
}

images[selectedCellIndexPath.item] = images
collectionView?.reloadData()
}

关于ios - 选择该单元格时如何将图像从照片库上传到特定的 Collection View 单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53405507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com