Swift NSMutableAttributedString addAttributes 的使用

10 min read

NSMutableAttributedString 是一个可以进行修改的富文本字符串,addAttributes 方法可以给字符串添加属性。

语法:

func addAttributes(_ attrs: [NSAttributedString.Key: Any], range: NSRange)

参数:

  • attrs: 属性字典,格式为 [NSAttributedString.Key: Any]。
  • range: 要修改的范围。

示例:

let str = "Hello World!"
let attributedStr = NSMutableAttributedString(string: str)

let range = NSRange(location: 0, length: 5)
let attributes: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.red,
    .font: UIFont.boldSystemFont(ofSize: 20)
]
attributedStr.addAttributes(attributes, range: range)

解释:

上述代码首先创建了一个普通的字符串 "Hello World!",然后使用 NSMutableAttributedString 将其转化为富文本字符串。在指定的范围内(即前 5 个字符),将字体颜色设置为红色,字体为粗体、大小为 20。最终的 attributedStr 就是修改后的富文本字符串。