RWP RWP - 4 months ago 24
Objective-C Question

UITextView setSelectedRange changes editable property

From the start, my

UITextView
with editable property to true is not editable (via settings in a NIB). The behaviour is such that a user can select and copy text but not edit. This is the way things should be.

However, if I make a call to
setSelectedRange
, a side effect is that the editable property is set to YES.

Setting it back to NO
[textview setEditable:NO]
scrolls to the bottom of the textView and undoes my programmatic selection. It also doesn't work, as editing becomes enabled anyway. The keyboard appears and everything.

I need to be able to select something programmatically and keep the textView in a state where users can only copy and select text.

[textView select:self];
[textView setSelectedRange:selectedText];


I'm stuck. Looking for any advice you can give.

This doesn't work:

[textView select:self];
[textView setSelectedRange:selectedText];
[textView setEditable:NO];


I've also tried setting the delegate function
textViewShouldBeginEditing
to return NO:

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
return NO;
}


That just locks everything down and I can't select any text.

Answer

This appears to work for me in a similar situation:

  • just let the textview be editable
  • [textView setDelegate:self];
  • [textView select:self];
  • [textView setSelectedRange:range];
  • add a function (BOOL)textView:shouldChangeTextInRange:replacementText: returning NO
  • and the final trick: assign an empty view as a keyboard for the textview, using:

textView.inputView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];