如何设置NSAttributedString的范围?

14

使用语法有点困惑。 我知道应该使用NSFontAttributeName,但是我不知道如何正确指定范围。

我对两种情况很好奇。

如何指定文本中所有字符的范围,以及如何将范围指定为前10个字符之类的内容。

有什么建议吗?

2个回答

27

不要使用魔数

let baseString = "Don't use magic numbers."

let attributedString = NSMutableAttributedString(string: baseString, attributes: nil)

let dontRange = (attributedString.string as NSString).range(of: "Don't")
attributedString.setAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)], range: dontRange)

如此元


我正在使用的字符串来自用户输入... 我正在使用UITextView,就像你使用UITextField一样。 - Stefan
所以我需要一个范围来表示字符串中的所有字符。 - Stefan
1
@stefan 如果你想影响整个字符串,只需将它们传递到我传递 nil 的位置即可。 - Fernando Mazzon
非常感谢,但如果我想用字典设置属性该怎么办? - Neko

6
在 XCode 10 和 Swift 4 中,我使用了以下方法:
let customizedText = NSMutableAttributedString(string: "My Text")
customizedText.addAttribute(NSAttributedString.Key.strokeWidth, value: 5.0, range: NSRange(location: 0, length: customizedText.string.count))
customizedText.addAttribute(NSAttributedString.Key.strokeColor, value: #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1), range: NSRange(location: 0, length: customizedText.string.count))
myLabel.attributedText = customizedText

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接