Thursday, August 6, 2009

Work Around For Text Fields and Tables

The code below will center your table cell and add some padding at the bottom so the user can scroll all the way to the top or bottom while a keyboard is up.

//////////Goes inside of your tablecontroller
- (void) textFieldDidBeginEditing:(UITextField*) textField
{
//add some padding
[self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 165, 0)];
//check to see if your text field is inside of a cell
//Note this will only work if you place the text field directly inside of the table cell.
if([[self.tableView indexPathsForRowsInRect:textField.superview.frame]count]>0)
{
//if we are inside a table cell then scroll to the middle of that cell
[self.tableView scrollToRowAtIndexPath:
[[self.tableView indexPathsForRowsInRect:textField.superview.frame]objectAtIndex:0]
atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
else
NSLog(@"no cell");
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
//if the user selected another text field we will not take any padding away
[self performSelector:@selector(animateKBDown) withObject:nil afterDelay:.001];
}
-(void) animateKBDown
{
//If you only have one text field then just forget about the array of text fields.
for (UITextField* tf in TEXTFIELDARRAY)
{
//if a textfield is selected then no further actions are needed
if([tf isFirstResponder])
return;
}
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:.3];
//animate the subtraction of padding
self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 0, 0);
[UIView commitAnimations];
}