Charlie Price Charlie Price - 1 year ago 97
iOS Question

textview - put cursor at end of text when start editing

I am editing text in a UITextView. When the field opens for editing I need the cursor to be positioned after the final character of the existing text. The behavior I see is that the cursor is positioned more or less under the point where I touch the UITextView to start editing -- perhaps at the end of the word I touch on. I have tried setting the textview.selectedRange in both textViewDidBeginEditing: and textViewShouldBeginEditing: but that had no effect at all. I tried selecting ranges of the existing text, like {1,2} and that didn't do anything either. It seems like the selectedRange is more-or-less a read-only value?

- (void) textViewDidBeginEditing:(UITextView *)textView {
// Position the insertion cursor at the end of any existing text
NSRange insertionPoint = NSMakeRange([textView.text length], 0);
textView.selectedRange = insertionPoint;

How do I get the cursor to the end of the text?

Answer Source

The post referred to by the comment by artud2000 contains a working answer. To summarize here, add:

EDIT: The original answer was not sufficient. I've added toggling the editable property which seems to be sufficient. The problem is that the tap gesture only goes to the handler a single time (at most) and subsequent taps on the UITextField start editing directly. If it isn't editable then the UITextView's gesture recognizers are not active and the one I placed will work. This may well not be a good solution but it does seem to work.

- (void)viewDidLoad {
    tapDescription = [[UITapGestureRecognizer alloc] 
        initWithTarget:self action:@selector(tapDescription:)];
    [self.descriptionTextView addGestureRecognizer:tapDescription];
    self.descriptionTextView.editable = NO;  // if not set in storyboard

- (void) tapDescription:(UIGestureRecognizer *)gr {
    self.descriptionTextView.editable = YES;
    [self.descriptionTextView becomeFirstResponder];

- (void) textViewDidEndEditing:(UITextView *)textView {
    //whatever else you need to do
    textView.editable = NO;

The default position of the cursor seems to be after any existing text which solved my problem, but if you want to you can select the text in textViewDidBeginEditing: by setting the selectedRange -- for instance:

- (void) textViewDidBeginEditing:(UITextView *)textView {
    // Example: to select the second and third characters when editing starts...
    NSRange insertionPoint = NSMakeRange(1, 2);
    textView.selectedRange = insertionPoint;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download