1

I have a UITableView that contains a series of text input fields, which can be UITextField or UITextView controls. When a text input field is selected, the keyboard's 'Next' button is used to cycle through the fields. This all works properly except for one thing. When a UITextView (multiline) receives focus by calling becomeFirstResponder, the cursor is positioned at the second line in the view, not the first. This seems to be the most common suggestion to address the issue, but it does not work in my case. Any suggestions? thanks!

-(void)textViewDidBeginEditing:(UITextView *)textView
{
     [textView setSelectedRange:NSMakeRange(0, 0)];
}

Also tried this without success:

textView.selectedTextRange = [textView textRangeFromPosition:textView.beginningOfDocument toPosition:textView.beginningOfDocument];
Pheepster
  • 6,045
  • 6
  • 41
  • 75

1 Answers1

2

It seems the cursor is repositioned after textViewDidBeginEditing is called; so you move it and it is moved back. You can get around this by calling setSelectedRange using dispatch_async:

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        textView.selectedRange = NSMakeRange(0, 0);
    });;
}

Update with your fix for future users as it seems another option works as well to fix the problem I mentioned, which was to performSelectorOnMainThread and call setCursor to move the cursor.

[self performSelectorOnMainThread:@selector(setCursor) withObject:nil waitUntilDone:NO];
chrissukhram
  • 2,957
  • 1
  • 13
  • 13
  • Your answer did prompt me to try the following, which did work: [self performSelectorOnMainThread:@selector(setCursor) withObject:nil waitUntilDone:NO]; – Pheepster Mar 27 '15 at 21:52
  • Awesome, so it seems the reason was correct but there are multiple options to try and resolve it depending on situations. Thanks for the update as it will help future users. Added to my answer. – chrissukhram Mar 27 '15 at 21:54