iOS UITableView or UIScrollView with keyboard input needs resigning

You want users to enter some data into a form or some input field. Well good for you! Sometimes it can become an interesting process to figure the right way to display, and then resign, that keyboard so it makes sense to the user. One instance I ran into recently was when I had a table view of options that required some number to be inputed as well as text in other areas. I played with several different ways to “hide” the keyboard. After reading some Apple docs I ran across the scroll view delegate method scrollViewWillBeginDragging.

-(IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    //editingField is a property of my class declared in my .h
    self.editingField = textField;    
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView 
{
    [editingField resignFirstResponder];
}

This is not going to always be the answer but for me it was perfect! Hope this helps one or two of you out there.

To add to that once you have a keyboard sometimes it will cover the text field or whatever you are trying to enter the information into. In that case you need to “move” or set the offset during the entering of data. For this I have:


-(IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.editingField = textField;    
    CGPoint point = [textField.superview convertPoint:textField.frame.origin toView:self.tableView];
    CGPoint contentOffset = self.tableView.contentOffset;
    //this requires some fiddling depending on OS, view, and keyboard
    contentOffset.y = (point.y - self.navigationController.navigationBar.frame.size.height) - 30;
    //print the value for testing
    NSLog(@" contentOffset is: %@", NSStringFromCGPoint(contentOffset));
    [self.tableView setContentOffset:contentOffset animated:YES];
}
This entry was posted in iOS, objective C. Bookmark the permalink.