ImagePicker选择图像后,CollectionView图像不会更新

时间:2017-05-27 08:07:21

标签: ios swift xcode uicollectionview uiimagepickercontroller

我有一个collectionView单元格,里面有一个图像。当用户点击图像时,图像选择器被启动。但是,选择图像时,collectionView中的图像不会更新。我在常规UIViewController中使用完全相同的代码并且它有效,所以我假设它是因为它在UICollectionViewController中。

以下是应该更新图片的代码:

func updateCollectionView(image: UIImage) {
    let indexPath = IndexPath(item: 3, section: 0)
    if let LoginCell = collectionView.cellForItem(at: indexPath) as? LoginCell {
        LoginCell.logoImageView.image = image
    }
    collectionView.reloadItems(at: [indexPath])
}

以下是委托功能:

weak var delegate: LoginControllerDelegate?

func updateCollectionView(image: UIImage) {
    delegate?.updateCollectionView(image: image)
}

这是将委托和updateCollectionView函数绑定在一起的picker函数:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])  {
    print(info)
    picker.delegate = self
    var selectedImageFromPicker: UIImage?

    if let editedImage = info["UIImagePickerControllerEditedImage"] {

        selectedImageFromPicker = editedImage as? UIImage

    } else if let originalImage = info["UIImagePickerControllerOriginalImage"] {
        selectedImageFromPicker = originalImage as? UIImage
    }

    if let selectedImage = selectedImageFromPicker {
        updateCollectionView(image: selectedImageFromPicker!)
    }
}

以下是collectionView方法,LoginCell是我试图调出选择器的地方:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
    return pages.count + 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if indexPath.item == pages.count{
        let loginCell = collectionView.dequeueReusableCell(withReuseIdentifier: loginCellId, for: indexPath) as! LoginCell
        loginCell.delegate = self
        return loginCell
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PageCell

    let page = pages[indexPath.item]
    cell.page = page

    return cell
}

这是我在协议中创建的委托方法:

protocol LoginControllerDelegate: class { func updateCollectionView(image: UIImage)

1 个答案:

答案 0 :(得分:0)

在方法的最后添加此代码。

if let selectedImage = selectedImageFromPicker, let yourCell = collectionView.cellForItem(at: IndexPath(item: 3, section: 0)) as? CustomCell {
    yourCell.logoImageView.image = selectedImage
    collectionView.reloadItems(at: [IndexPath(item: 3, section: 0)])
}

这将获得您的单元格的引用,更新其logoImageView并重新加载该项目。