首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NSRange异常iOS

NSRange异常iOS
EN

Stack Overflow用户
提问于 2018-06-10 14:02:08
回答 1查看 1.2K关注 0票数 0

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

由于非正常异常“NSRangeException”终止应用程序,原因:“NSMutableRLEArray objectAtIndex:effectiveRange::bounds”

代码语言:javascript
运行
复制
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
    }
}

我不知道它能不能修好

我试过:

代码语言:javascript
运行
复制
NSRange
NSMakeRange(loc: 0, mytext.count)

还缺什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-10 15:14:04

范围的问题是由于属性化字符串是空的。你从来没有给过它最初的文本。

更改:

代码语言:javascript
运行
复制
let stringFormatted = NSMutableAttributedString()

至:

代码语言:javascript
运行
复制
let stringFormatted = NSMutableAttributedString(string: code.statusType.title)

那么你所拥有的范围就能工作了。当然,这是计算整个字符串范围的一种奇怪的方法。只需做:

代码语言:javascript
运行
复制
let range = NSRange(location: 0, length: (code.statusType.title as NSString).length)

但是,当属性应用于整个字符串时,创建属性字符串的方法要简单得多:

代码语言:javascript
运行
复制
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
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50784486

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档