iOS NSAttributedString因cell 复用产生的问题

探讨在UITableView中使用NSAttributedString设置部分cell为富文本,而其余为普通文本时遇到的复用问题。若不正确处理,会导致滚动后部分cell文本颜色异常。文章提供了修正方法,即在非富文本cell中也使用NSAttributedString。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

部分cell中的label需要设置富文本属性,部分不需要。在使用NSAttributedString后,复用的cell同样具有相同效果。

错误使用举例:

 cell.lCost.text = ""
 cell.lCost.attributedText = nil
 if indexPath.row == 10 {
     let att = NSAttributedString(string: "\(indexPath.row)", attributes: [NSAttributedString.Key.foregroundColor:UIColor.red, .underlineStyle:NSUnderlineStyle.single.rawValue])
     cell.lCost.attributedText = att
  } else {
     cell.lCost.text = "\(indexPath.row)"
 }

效果:除了row=10的字体颜色是红色外,下滑滚动后部分cell的字体颜色同样是红色。虽然设置了attributedText=nil,但在前面设置了text = "",使得之前的富文本属性被引用,被保留下来。此现象在iOS10及以前不会存在。

解决方法:删除text = ""

if indexPath.row == 10 {
   let att = NSAttributedString(string: "\(indexPath.row)", attributes: [NSAttributedString.Key.foregroundColor:UIColor.red, .underlineStyle:NSUnderlineStyle.single.rawValue])
    cell.lCost.attributedText = att
 } else {
    cell.lCost.attributedText =  NSAttributedString(string: "\(indexPath.row)")
 }

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值