swift - 使用 UIImagePickerController 更改自定义单元格的图像
问题描述
我创建了一个imageView
内部的自定义单元格。我想image
在imageView
. 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)
}
解决方案
您正在这里创建一个新单元格:
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
)
推荐阅读
- javascript - 如果我们可以在 javascript 中的原型对象上定义字段,我们为什么要在 javascript 中使用静态字段
- javascript - 通过 Cordova 在 android / iOS 上运行时,Framework7 单选组按钮不起作用
- python-3.x - 以日期时间格式使用 if 条件
- python - 为什么 mypy 会忽略包含与 TypeVar 不兼容的类型的泛型类型变量?
- java - 警报对话框未显示在 MapsActivity 中
- elasticsearch - 如何使用 query_string 匹配确切的单词
- spring - 修复 StreamListener 常量 Channel Name 的解决方法
- bash - 使用 .sh 脚本进行 docker 健康检查
- python - 为什么可以使用 PyCharm 从代码中而不是从 shell 中抑制 InsecureRequestWarning
- aws-cdk - AWS CDK 中是否可以将 CodeBuild 项目与 VPC、子网和安全组相关联?