如何设置 NSAttributedString 范围?
How to set NSAttributedString range?
对语法的使用有点困惑。
我知道你应该使用 NSFontAttributeName,但我不知道如何正确指定范围。
我很好奇两个案例
如何指定文本中所有字符的范围,以及如何将范围指定为前 10 个字符。
有什么建议吗?
不要使用幻数
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)
所以元
在XCode10和swift4中我是这样使用的:
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
对语法的使用有点困惑。 我知道你应该使用 NSFontAttributeName,但我不知道如何正确指定范围。
我很好奇两个案例
如何指定文本中所有字符的范围,以及如何将范围指定为前 10 个字符。
有什么建议吗?
不要使用幻数
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)
所以元
在XCode10和swift4中我是这样使用的:
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