Force UITextView cursor to the top of the view

若如初见. 提交于 2021-02-11 05:33:14

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/29310035/force-uitextview-cursor-to-the-top-of-the-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!