如何设置NSAttributedString范围?

问题描述 投票:6回答:2

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

我很好奇两个案例。

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

有什么建议?

ios swift nsattributedstring
2个回答
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
投票

在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
© www.soinside.com 2019 - 2024. All rights reserved.