Setting attributedText, NSRangeException error

心不动则不痛 提交于 2019-12-10 22:32:20

问题


Trying to set my UIText view's attributed text properties via selection. Almost works. Action to set text with red font color below. This works sometimes, but often gives an error:

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds'

This happens even while there seems to be many more characters in the text view than indicated by the selected range.

- (IBAction)setText:(id)sender {

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithAttributedString:myTextView.attributedText];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(p1,p2)];

    myTextView.attributedText = string;

}

p1 and p2 are the start and end of the selected text. They are generated with the code below, which seems to work as expected:

- (void)textViewDidChangeSelection:(UITextView *)textView {

    UITextRange *selectedRange = [myTextView selectedTextRange];

    p1 = [myTextView offsetFromPosition:myTextView.beginningOfDocument toPosition:[selectedRange start]];
    p2 = [myTextView offsetFromPosition:myTextView.beginningOfDocument toPosition:[selectedRange end]];

 }

EDIT: I fixed the problem after reading @borrrden's comment. Instead of NSMakeRange(p1,p2)] I am using NSMakeRange(p1,p2-p1)].


回答1:


You need to be careful about NSMakeRange. I've answered another question with the same answer before, but it takes a start value and a length value, not a start value and an end value as you are trying to use it.



来源:https://stackoverflow.com/questions/15653947/setting-attributedtext-nsrangeexception-error

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