简体   繁体   中英

becomeFirstResponder: automatically scroll to the UIControl that becomes first responder

I have a grouped UITableViewController with one section and many rows. Each cell consists of two elements: a UILabel with a description and a UITextField for an input. A form, I would say.

On the bottom is a button "Next" the go to the next view. But before that, I validate the UITextField 's: if the user hasn't filled a field, this field should get the focus, so that the user sees that he needs to enter something. I tried with this:

[inputField becomeFirstResponder];

Remember, the button I pressed is on the bottom of my view and imagine that the UITextField is on the top . In this situation, the field doesn't get the focus because it is too far away. Now when I scroll up slowly and the field gets visible, the field becomes first responder and gets the cursor :-) Conclusion: The becomeFirstResponder worked, but does not exactly do what I wanted to. I don't want to scroll up with my finger, the field should get the focus and visible automatically.

Is there any way to "jump" directly to my field? Use an alternative to becomeFirstResponder ? Scroll to my field automatically?

Thanks for your help!

If you know the index of cell with the UITextField you want to edit, use



NSIndexPath* indexPath = [[NSIndexPath indexPathWithIndex:your_section_index] indexPathByAddingIndex:your_cell_index];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]

before you call becomeFirstResponder .

If the cell is off the screen, becomeFirstResponder may fail for some versions of iOS. In addition, some versions will perform additional scrolling on the tableview in some situations (eg if Apple's code determines that the responder would still be off the screen without more scrolling). To get around these issues, you may need to call become first responder after the scroll animation is complete.

I'd the same issue. it is due to the UIAnimation occurring for the two tasks simultaneously . So while the UIAnimation for scrollToRowAtIndexPath ignores the becomeFirstResponder .

The solution might be disable the Animation effect one of it OR else using the performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:1.0f]; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM