gpt4 book ai didi

ios - iOS NSRange 异常

转载 作者:行者123 更新时间:2023-11-30 11:25:27 25 4
gpt4 key购买 nike

这是我的代码:我正在尝试格式化我的文本 NSMutableAttributedString(),但它似乎总是超出范围。

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of 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)

请问还缺少什么?

最佳答案

您的范围问题是由于您的属性字符串为空。您从未给它初始文本。

更改:

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
}
}

关于ios - iOS NSRange 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50784486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com