这是我的代码:我试图格式化我的文本NSMutableAttributedString(),但它似乎总是超出范围。
由于非正常异常“NSRangeException”终止应用程序,原因:“NSMutableRLEArray objectAtIndex:effectiveRange::bounds”
extension ImageTableViewCell {
func formatLabel(code: SectionItem) {
print(code.statusType.title)
let stringFormatted = NSMutableAttributedString()
let range = (code.statusType.title as NSString).range(of: code.statusType.title)
print(range); stringFormatted.addAttribute(NSAttributedStringKey.foregroundColor, value: code.statusType.color, range:range)
stringFormatted.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: range)
self.titleLabel.attributedText = stringFormatted
}
}
我不知道它能不能修好
我试过:
NSRange
NSMakeRange(loc: 0, mytext.count)
还缺什么?
发布于 2018-06-10 15:14:04
范围的问题是由于属性化字符串是空的。你从来没有给过它最初的文本。
更改:
let stringFormatted = NSMutableAttributedString()
至:
let stringFormatted = NSMutableAttributedString(string: code.statusType.title)
那么你所拥有的范围就能工作了。当然,这是计算整个字符串范围的一种奇怪的方法。只需做:
let range = NSRange(location: 0, length: (code.statusType.title as NSString).length)
但是,当属性应用于整个字符串时,创建属性字符串的方法要简单得多:
extension ImageTableViewCell {
func formatLabel(code: SectionItem) {
let attributes = [ NSAttributedStringKey.foregroundColor: code.statusType.color, NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue ]
let stringFormatted = NSAttributedString(string: code.statusType.title, attributes: attributes)
self.titleLabel.attributedText = stringFormatted
}
}
https://stackoverflow.com/questions/50784486
复制相似问题