首页 > 解决方案 > 使用 UIImagePickerController 更改自定义单元格的图像

问题描述

我创建了一个imageView内部的自定义单元格。我想imageimageView. UIImagePickerController当我在模拟器中检查此功能时,它不会改变任何东西。无法弄清楚问题所在。

自定义单元格的属性:

let imageOfPlace: UIImageView = {
    let iv = UIImageView()
    return iv
}()

中的单元格tableView

let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: ImageOfPlaceViewCell.identifierOfImageOfPlaceCell) as! ImageOfPlaceViewCell

选择器功能:

func chooseImagePickerController(source: UIImagePickerController.SourceType) {
    if UIImagePickerController.isSourceTypeAvailable(source) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = source
        present(imagePicker, animated: true)
    }
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    let myCell = ImageOfPlaceViewCell()
    myCell.imageOfPlace.image = info[.editedImage] as! UIImage
    picker.dismiss(animated: true)
}

标签: swifttableviewuiimagepickercontroller

解决方案


您正在这里创建一个新单元格:

let myCell = ImageOfPlaceViewCell()

取而代之的是,您需要更改现有单元格的图像。您需要从表中获取现有的单元格对象。为此,您可以使用tableView.cellForRow,并在那里传递您的行的索引路径。

我不确定您的表格结构,但您还需要确保在重新加载表格时它不会消失,因此您可以将选取的图像存储在其他地方以供下次在cellForRowAt.

var pickedImage: UIImage?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: ImageOfPlaceViewCell.identifierOfImageOfPlaceCell) as! ImageOfPlaceViewCell
        cell.imageOfPlace.image = pickedImage
    }
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
    let image = info[.editedImage] as! UIImage
    pickedImage = image

    let myCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0))

    myCell?.imageOfPlace.image = info[.editedImage] as! UIImage

    picker.dismiss(animated: true)
}

ps 另外我不确定let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!在你的 if 之前这是什么,它可能是多余的(至少在你从那个返回单元格的情况下if


推荐阅读