Why does setting an attributedText's background raise an NSRangeException error?

China☆狼群 提交于 2019-12-13 21:57:25

问题


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:


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


来源:https://stackoverflow.com/questions/34148778/why-does-setting-an-attributedtexts-background-raise-an-nsrangeexception-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!