0

So I'm trying to set a blue background color to a UILabel's attributed text dynamically as the user pans their finger along the screen but I can't for the life of me figure out why I'm getting an NSRangeException with the following error message: Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds at times.

Here's my code:

var afterContext = ""                    
    if textDocumentProxy.documentContextAfterInput != nil {
       afterContext = textDocumentProxy.documentContextAfterInput!
    } else {
       afterContext = ""
    }

    if beforeContext != nil {              
        if initialContext == nil {                                         
            myRange = NSRange(location: 0, length:afterContext.characters.count)

           let attrString = NSMutableAttributedString(string: selectedTextView.text!)
           attrString.addAttribute(NSBackgroundColorAttributeName, value: UIColor(red: 20/255, green: 111/255, blue: 225/255, alpha: 1), range: myRange)
        }
     }
cyril
  • 3,020
  • 6
  • 36
  • 61

1 Answers1

0

This simple if condition seemed to have fixed it for good

if afterContext.characters.count > 0 {
   myRange = NSRange(location: 0, length: afterContext.characters.count-1)
} else {
   myRange = NSRange(location: 0, length: afterContext.characters.count)
}
cyril
  • 3,020
  • 6
  • 36
  • 61