使用UIImagePickerController修改自定义cell的UIImageView图片不生效问题
问题原因及修复方案
核心错误点
- 你在
imagePickerController代理方法里手动实例化了一个全新的ImageOfPlaceViewCell对象,这个对象和当前TableView上渲染的、你要修改的cell没有任何关联,修改它的image属性自然不会在界面上有任何反馈 - 没有做数据持久化存储:Cell是复用组件,不能直接作为存储图片的载体,即使你拿到了真实的cell,滚动TableView时图片也会消失
- 补充检查点:你定义的
imageOfPlace没有设置frame、约束、contentMode等属性,也没有添加到cell的contentView上,即使赋值了图片也可能无法正常显示
修复步骤
第一步:新增变量存储选中的图片
在你的ViewController类中新增一个可选UIImage属性,用来保存用户选中的图片:
var selectedPlaceImage: UIImage?
第二步:修改图片选择代理方法的逻辑
不要新建cell,把选中的图片赋值给上面新增的存储属性,然后刷新TableView的对应行:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // 取出编辑后的图片赋值给存储属性 selectedPlaceImage = info[.editedImage] as? UIImage picker.dismiss(animated: true) // 刷新第0行的cell(对应你自定义的图片cell位置) tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none) }
第三步:修改Cell复用的赋值逻辑
在你配置cell的地方,把存储的图片赋值给cell的imageView:
if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: ImageOfPlaceViewCell.identifierOfImageOfPlaceCell) as! ImageOfPlaceViewCell // 新增赋值逻辑,没有选中图片时可以显示占位图 cell.imageOfPlace.image = selectedPlaceImage ?? UIImage(named: "你的占位图名称") return cell } // 其他行的cell逻辑...
第四步:补全自定义Cell中UIImageView的配置
给imageOfPlace添加必要的约束、显示配置,并且加到cell的contentView上:
let imageOfPlace: UIImageView = { let iv = UIImageView() iv.contentMode = .scaleAspectFill iv.clipsToBounds = true iv.translatesAutoresizingMaskIntoConstraints = false return iv }() // 在cell的初始化方法中添加约束,参数可按需调整 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(imageOfPlace) NSLayoutConstraint.activate([ imageOfPlace.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16), imageOfPlace.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), imageOfPlace.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12), imageOfPlace.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12), imageOfPlace.heightAnchor.constraint(equalToConstant: 200) ]) }
额外注意事项
你原有代码中tableView的cell复用逻辑存在冗余,外层的let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!没有实际作用,还会造成不必要的性能消耗,建议删除,直接按indexPath的判断返回对应cell即可。
内容的提问来源于stack exchange,提问作者julia117
相关产品推荐
相关产品推荐

