如何设置NSAttributedString范围?

Ste*_*fan 6 nsattributedstring ios swift

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

我很好奇两个案例.

如何指定文本中所有字符的范围,以及如何将范围指定为前10个字符.

有什么建议?

Fer*_*zon 17

不要使用魔术数字

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)
Run Code Online (Sandbox Code Playgroud)

所以meta


Mah*_*asi 5

在 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
Run Code Online (Sandbox Code Playgroud)