如何设置NSAttributedString范围?

时间:2017-06-02 16:27:32

标签: ios swift nsattributedstring

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

我很好奇两个案例。

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

有什么建议吗?

2 个答案:

答案 0 :(得分:16)

不要使用魔术数字

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)

所以meta

答案 1 :(得分:1)

在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