【问题标题】:How to upload image from photolibrary to specific collectionview cell when that cell is selected?选择该单元格时,如何将图像从照片库上传到特定的 collectionview 单元格?
【发布时间】:2018-11-21 04:57:39
【问题描述】:

我希望能够允许用户在选择时将图像从照片库上传到 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()
}

【问题讨论】:

  • 看代码感觉可以简单的把cell对象从didselect方法传给cellTapped方法。一旦你有可用的单元格对象,你可以在它被选中 uiimagepicker 后将图像分配给它。这是你想要的吗?如果您需要其他解决方案,请告诉我。
  • @tendstoZero 谢谢。我想这就是我要找的。但我不确定如何编写代码。您的帮助将不胜感激。

标签: ios swift uicollectionview uiimagepickercontroller


【解决方案1】:

您需要记住在选择图像之前点击了哪个单元格。您可以将索引保存在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()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    相关资源
    最近更新 更多