如何在 swift 3 中使用 addAttribute 和 NSRANGE

How do I uses addAttribute and NSRANGE in swift 3

您好,我正在尝试在 Swift3 中使用 addAttribute

我只想将 IDNAME 设置为粗体。

这是我正在尝试的。

let boldUsername = NSMutableAttributedString(string: "IDNAME hi nice 2 meet you :D #HELLOW")


//            boldUsername.addAttribute(NSFontAttributeName, value: UIFont(name: "SFUIText-Bold", size: 14)!, range: (boldUsername.string as NSString).range(of: " "))

            boldUsername.addAttribute(NSFontAttributeName, value: UIFont(name: "SFUIText-Bold", size: 14)!, range: NSRange(location: 0, length: 5))

如何获取每次不同的 IDNAME 索引?

-> 有没有办法拆分 space 并获取索引?

你需要做这样的事情。

let personName = "Black"
let wholeStr = "\(personName) hi nice 2 meet you :D #HELLOW"
let boldUsername = NSMutableAttributedString(string: wholeStr)
boldUsername.addAttribute(NSFontAttributeName, value: UIFont(name: "SFUIText-Bold", size: 14)!, range: (wholeStr as NSString).range(of: personName))