Why does setting an attributedText's backgroun

2019-09-10 23:36发布

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

1条回答
The star\"
2楼-- · 2019-09-11 00:07

This simple if condition seemed to have fixed it for good

查看更多
登录 后发表回答