【问题标题】:NSRange Exception iOSNSRange 异常 iOS
【发布时间】:2018-06-10 14:02:08
【问题描述】:

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

由于未捕获的异常“NSRangeException”而终止应用程序,原因:“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)

请问还有什么遗漏的?

【问题讨论】:

    标签: ios swift nsattributedstring


    【解决方案1】:

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

    变化:

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

    【讨论】:

      猜你喜欢
      • 2013-11-07
      • 1970-01-01
      • 2012-05-26
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多