问题
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