我建立了一个简单的游乐场来演示我在检索属性字符串的属性时遇到的问题。也许我不明白如何定义范围:也许我错过了其他东西。
我定义了一个 NSMutableAttributedString,它有两种颜色,并将字体更改为粗体(蓝色)和斜体(红色):
var someText = NSMutableAttributedString()
let blueAttri : [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12), NSAttributedString.Key.foregroundColor : UIColor.blue]
let redAttri : [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.italicSystemFont(ofSize: 12), NSAttributedString.Key.foregroundColor : UIColor.red]
someText = NSMutableAttributedString(string: "Some blue string here; ", attributes: blueAttri)
someText.append(NSMutableAttributedString(string: "Some red string here; ", attributes: redAttri))
Run Code Online (Sandbox Code Playgroud)
此时,字符串看起来很好,显示两种颜色的文本。
然后我定义了 3 个范围(尝试不同的方法来定义范围。)
var range1 = NSRange()
var range2 = NSRange(location: 0, length: someText.length)
var range3 = NSRange(location: 40, length: 44)
Run Code Online (Sandbox Code Playgroud)
最后,我尝试检索文本的属性
// retrieve attributes
let attributes1 = someText.attributes(at: 0, …Run Code Online (Sandbox Code Playgroud)