在一个属性字符串中使用多个样式

时间:2018-01-26 08:41:17

标签: ios swift nsattributedstring

let myString = text1 + " (\(text2) people added)"
let myAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
cell.textLabel?.attributedText = myAttrString

如何在一个属性字符串中使用不同样式的text1" (\(text2) people added)"

1 个答案:

答案 0 :(得分:3)

是的,你可以

    var attributedText = NSMutableAttributedString()
    let str1 = text1
    let str2 = " (\(text2) people added)"
    let attr1 = [NSAttributedStringKey.foregroundColor: UIColor.blue]
    let attr2 = [NSAttributedStringKey.foregroundColor: UIColor.red]
    attributedText.append(NSAttributedString(string: str1, attributes: attr1))
    attributedText.append(NSAttributedString(string: str2, attributes: attr2))

    cell.textLabel?.attributedText = attributedText