将图像从图像选择器上传到单元格

时间:2018-12-12 20:51:06

标签: ios swift uicollectionview uiimagepickercontroller

在集合视图中点击一个单元格时,我会调用图像选择器:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    switch indexPath.row {
    case 2:
        imagePicker.delegate = self
        imagePicker.sourceType = .savedPhotosAlbum;
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    default:
        break
    }
}

然后我想将图像上传到单元格的imageView中:

 func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
    self.dismiss(animated: true, completion: { () -> Void in
    })
    //imageView.image = image   ---> need imageview in a cell wit indexpath = 2
}

我如何实现委托和协议?

2 个答案:

答案 0 :(得分:1)

您可以尝试

选项1

 arr[2] = image
 let cell = collectionView.cellForItem(at:IndexPath(row:2,section:0)) as! cellName 
 cell.imageView.image = image

选项2(推荐),因为访问表外的单元格是一个坏主意

是在模型中编辑图像,然后重新加载表/ indexPath

func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
  self.dismiss(animated: true, completion:nil)
  arr[2] = image
  let indexPath = IndexPath(item: 2, section: 0) 
  self.collectionView.reloadItems(at: [indexPath])
}

cellForItemAt应该有

let cell = ///
cell.imageView.image = arr[indexPath.row]

答案 1 :(得分:0)

在图像选择器委托中,您需要更新用于填充集合视图的数据模型。然后,您告诉集合视图重新加载该关联的行。

这当然假设您编写了cellForItemAt,以根据数据模型适当设置单元格的图像。