如何在单个NSAttributedString中为text1与附加文本设置不同样式?
解决不同文本片段设置不同样式的问题
嘿,这事儿好办!你现在的写法是给整个拼接后的字符串套了同一种样式,要分开控制text1和后缀部分的样式,得用NSMutableAttributedString来逐个拼接带独立样式的文本片段。我给你写个具体的实现例子:
// 第一步:分别定义两个部分的样式(可以按需调整颜色、字体等属性) let text1Attributes: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.black, // 这里设置text1的颜色,比如黑色 .font: UIFont.systemFont(ofSize: 16, weight: .regular) // 可选:设置text1的字体 ] let suffixAttributes: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.blue, // 后缀部分用你原来的蓝色 .font: UIFont.systemFont(ofSize: 14, weight: .light) // 可选:给后缀设置不同字体来区分 ] // 第二步:创建可变富文本对象,逐个添加带样式的文本片段 let combinedAttributedString = NSMutableAttributedString() // 添加text1部分 combinedAttributedString.append(NSAttributedString(string: text1, attributes: text1Attributes)) // 拼接后缀文本并添加 let suffixText = " (\(text2) people added)" combinedAttributedString.append(NSAttributedString(string: suffixText, attributes: suffixAttributes)) // 第三步:把最终的富文本赋值给cell的文本标签 cell.textLabel?.attributedText = combinedAttributedString
额外说明:
你可以根据自己的需求,在text1Attributes和suffixAttributes里添加更多属性,比如下划线(.underlineStyle)、字间距(.kern)等等,完全能实现更丰富的文本样式区分。
内容的提问来源于stack exchange,提问作者Utku Dalmaz
相关产品推荐
相关产品推荐

