Pheepster
Pheepster

Reputation: 6357

Force UITextView cursor to the top of the view

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];

Upvotes: 1

Views: 597

Answers (1)

chrissukhram
chrissukhram

Reputation: 2967

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];

Upvotes: 2

Related Questions