如何为UILabel(非UITextView)的NSMutableAttributedString设置文本圆角背景
UILabel实现富文本指定段圆角背景的落地方案
系统原生NSAttributedString的backgroundColor属性仅支持渲染直角实心矩形背景,无内置圆角配置项。在保持使用UILabel、不引入UITextView的前提下,可通过自定义UILabel子类接管文本绘制流程实现圆角背景效果,无额外第三方依赖,适配UITableViewCell复用逻辑:
具体实现步骤
- 第一步:定义自定义富文本属性标识,用于标记需要绘制圆角背景的文本范围
extension NSAttributedString.Key { /// 自定义标识:存储圆角背景色 static let roundedBackgroundColor = NSAttributedString.Key("roundedBackgroundColor") }
- 第二步:编写支持圆角背景绘制的UILabel子类
class RoundedBackgroundLabel: UILabel { override func drawText(in rect: CGRect) { guard let originalAttr = attributedText else { super.drawText(in: rect) return } let fullRange = NSRange(location: 0, length: originalAttr.length) // 移除系统默认的直角背景,避免和自定义圆角背景重叠 let mutableAttr = NSMutableAttributedString(attributedString: originalAttr) mutableAttr.removeAttribute(.backgroundColor, range: fullRange) attributedText = mutableAttr // 准备布局管理器,用于计算文本段的实际绘制位置 let textStorage = NSTextStorage(attributedString: mutableAttr) let layoutManager = NSLayoutManager() let textContainer = NSTextContainer(size: bounds.size) textContainer.lineFragmentPadding = 0 layoutManager.addTextStorage(textStorage) layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) // 遍历所有需要绘制圆角背景的文本段 mutableAttr.enumerateAttribute(.roundedBackgroundColor, in: fullRange) { value, range, _ in guard let bgColor = value as? UIColor else { return } // 获取该文本段在每行上的实际绘制范围,自动适配换行场景 layoutManager.enumerateEnclosingRects( forGlyphRange: range, withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0), in: textContainer ) { lineRect, _ in // 给背景添加内边距,避免紧贴文字 let bgRect = lineRect.insetBy(dx: -2, dy: -2) // 绘制带圆角的填充背景 let bgPath = UIBezierPath(roundedRect: bgRect, cornerRadius: 4) bgColor.setFill() bgPath.fill() } } // 最后绘制文本本身 super.drawText(in: rect) } }
- 第三步:修改原有富文本拼接逻辑
移除原有append语句末尾的多余语法点,将原来设置直角背景的.backgroundColor属性替换为自定义的.roundedBackgroundColor属性:
// 原有直角背景写法(带语法错误) // attr.append(NSAttributedString(string: " false condition ", attributes: [.backgroundColor: dynamicBackground])). // 修改后的写法 attr.append( NSAttributedString( string: " false condition ", attributes: [.roundedBackgroundColor: dynamicBackground] ) )
- 第四步:替换UITableViewCell内的原生Label
在自定义代码展示Cell中,将系统默认的UILabel替换为上述RoundedBackgroundLabel子类,通过AutoLayout设置好约束适配内容高度,正常赋值拼接完成的富文本即可。
可调效果参数
- 圆角半径:调整
UIBezierPath(roundedRect:bgRect, cornerRadius: 4)中的cornerRadius值,可自定义圆角大小 - 背景内边距:调整
insetBy(dx: -2, dy: -2)的偏移值,优化蓝色背景与文字的间距 - 代码展示优化:建议统一使用等宽字体,保证代码缩进对齐效果更自然
内容的提问来源于stack exchange,提问作者Antonio A. Chavez
相关产品推荐
相关产品推荐

