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)].

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top