swift - 如何在 swift 3 中使用 addAttribute 和 NSRANGE

标签 swift swift3 nsattributedstring nsrange addattribute

您好,我正在尝试在 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 的索引,即每次都不同?

->有没有办法分割空间并获取索引?

最佳答案

你需要做这样的事情。

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))

关于swift - 如何在 swift 3 中使用 addAttribute 和 NSRANGE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804584/

相关文章:

iphone - iPhone 中的高级搜索实现?

ios - UIScrollView:键盘以交互方式关闭

ios - CloudKit Query 适用于 Xcode 发布版本,不适用于 TestFlight

swift - 参数标签与任何可用的重载都不匹配

ios - 以编程方式选择选项卡自定义选项卡栏ios

ios - -fontWithSize 返回不同的字体对象

swift - 用 AVAudioRecorder 生成 AVAudioPCMBuffer

iphone - 在 Swift 后台下载

ios - swift 3 : Do I need to link the viewDidAppear function in storyboard?

swift - 使用 attributedText 在 UITextView 中实现撤消和重做