Swift中如何为TableViewCell右侧添加图标或自定义图片
问题描述
尝试为TableViewCell右侧添加类似WhatsApp静音图标样式的图标,但图标未在单元格中显示。以下是两段尝试代码:
第一段代码
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) var content = cell.defaultContentConfiguration() let countryNames = Array(countryInfos.keys) content.text = countryNames[indexPath.row] cell.contentConfiguration = content let myImage = UIImage(named:"star") cell.imageView?.image = myImage return cell }
第二段代码
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() var content = cell.defaultContentConfiguration() let countryNames = Array(countryInfos.keys) content.text = countryNames[indexPath.row] cell.contentConfiguration = content let myImage = UIImage(named:"star") cell.imageView?.image = myImage return cell }
注:star图片已存放于Assets文件夹中,文件名为star.png。
当前UI

预期UI

需求:让图标正常显示并置于单元格右侧。
解决方案
问题分析
- 第一段代码将
tableView.register放在cellForRowAt方法内,每次创建单元格都会重复注册,逻辑混乱且无效,注册操作应放在viewDidLoad中执行。 cell.imageView是单元格左侧的图片容器,要实现右侧图标,需使用单元格的accessoryView或UIListContentConfiguration的accessory属性。- 第二段代码直接创建
UITableViewCell实例,未使用复用机制,会导致性能问题,且未处理右侧图标的正确展示逻辑。
正确实现代码
步骤1:在viewDidLoad中完成单元格注册
override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") }
步骤2:修改cellForRowAt方法,实现右侧图标
方式一:使用UIListContentConfiguration的accessory(iOS14+推荐)
利用系统内容配置直接设置右侧附件图标,适配性更强:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) var content = cell.defaultContentConfiguration() let countryNames = Array(countryInfos.keys) content.text = countryNames[indexPath.row] // 设置右侧图标 if let starImage = UIImage(named: "star") { content.accessory = .customView(configuration: UIImageView.Configuration(image: starImage)) } cell.contentConfiguration = content return cell }
方式二:自定义accessoryView
手动创建UIImageView作为单元格右侧附件:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) var content = cell.defaultContentConfiguration() let countryNames = Array(countryInfos.keys) content.text = countryNames[indexPath.row] cell.contentConfiguration = content // 创建右侧图标视图并设置尺寸 let starImageView = UIImageView(image: UIImage(named: "star")) starImageView.frame = CGRect(x: 0, y: 0, width: 24, height: 24) cell.accessoryView = starImageView return cell }
额外注意事项
- 若需要保留图标原始颜色,可使用
UIImage(named: "star")?.withRenderingMode(.alwaysOriginal)。 - 若需图标支持点击,可结合
tableView(_:accessoryButtonTappedForRowWith:)方法处理点击事件。
内容的提问来源于stack exchange,提问作者ZeldaaaZonk
相关产品推荐
相关产品推荐

