UITableViewCell内UILabel无法移除strikethrough删除线属性求助
问题解答
核心错误点
didSelectRowAt方法中调用dequeueReusableCell(withIdentifier:for:)获取的是全新的复用cell,并非屏幕上当前正在显示的对应行的cell,修改该cell属性不会生效。- 没有存储已点击行的状态,调用
reloadData后cellForRowAt会重新给所有行的cell添加删除线,直接覆盖了临时修改的内容。 - 普通UILabel可以正常生效的原因是你持有了当前正在渲染的UILabel实例,修改直接作用于生效的视图,也没有刷新逻辑覆盖修改结果,和TableView的数据源驱动渲染、cell复用逻辑完全不同。
修复代码
import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var tableData = ["Green tomatoes", "Yellow bananas", "Red peppers"] // 新增存储已点击行的集合,记录哪些行需要去掉删除线 var selectedRows = Set<Int>() let cellId = "cellID" override func viewDidLoad() { super.viewDidLoad() let tableview = UITableView(frame: CGRect(x: 0, y: 200, width: view.frame.width, height: view.frame.height)) tableview.register(UITableViewCell.self, forCellReuseIdentifier: cellId) tableview.rowHeight = 40 tableview.delegate = self tableview.dataSource = self view.addSubview(tableview) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) cell.backgroundColor = #colorLiteral(red: 0.7176730633, green: 0.9274803996, blue: 0.9678700566, alpha: 1) // 根据状态判断是否添加删除线 if selectedRows.contains(indexPath.row) { cell.textLabel?.attributedText = tableData[indexPath.row].removeStrikeThrough() } else { cell.textLabel?.attributedText = tableData[indexPath.row].addStrikeThrough() } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 取消选中状态(可选) tableView.deselectRow(at: indexPath, animated: true) // 更新状态 selectedRows.insert(indexPath.row) // 只刷新当前行,性能更好 tableView.reloadRows(at: [indexPath], with: .automatic) } } extension String { func addStrikeThrough() -> NSAttributedString { let attributeString = NSMutableAttributedString(string: self) attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSRange(location: 0, length: attributeString.length)) attributeString.addAttribute(NSAttributedString.Key.strikethroughColor, value: UIColor.red, range: NSMakeRange(0, attributeString.length)) return attributeString } func removeStrikeThrough() -> NSAttributedString { let attributeString = NSMutableAttributedString(string: self) attributeString.removeAttribute(NSAttributedString.Key.strikethroughStyle, range: NSMakeRange(0, attributeString.length)) return attributeString } }
内容的提问来源于stack exchange,提问作者Kaplan
相关产品推荐
相关产品推荐

