Search code examples
iosswiftnsattributedstring

NSRange Exception iOS


this is my code: I am trying to format my text NSMutableAttributedString(), but it always seems to be out of range.

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

I don't know it can be fixed

I have tried:

NSRange
NSMakeRange(loc: 0, mytext.count)

What else is missing please?


Solution

  • Your issue with the range is due to the fact that your attributed string is empty. You never gave it the initial text.

    Change:

    let stringFormatted = NSMutableAttributedString()
    

    to:

    let stringFormatted = NSMutableAttributedString(string: code.statusType.title)
    

    Then the range you have would work. Of course that's an odd way of calculating the range of the entire string. Simply do:

    let range = NSRange(location: 0, length: (code.statusType.title as NSString).length)
    

    But there is a much simpler way to create an attribute string when the attributes should be applied to the whole string:

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