簡體   English   中英

選擇該單元格后,如何將其從圖像庫上傳到特定的collectionview單元格?

[英]How to upload image from photolibrary to specific collectionview cell when that cell is selected?

我希望能夠允許用戶在選擇圖片后將其從圖片庫上傳到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()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM