views:

12768

answers:

13

Hi all,

after a lot of trial and error, I'm giving up and asking the question. I've seen a lot of people with similar problems but can't get all the answers to work right.

I have a UITableView which is composed of custom cells. The cells are made of 5 text fields next to each other (sort of like a grid).

When I try to scroll and edit the cells at the bottom of the UITableView, I can't manage to get my cells properly positioned above the keyboard.

I have seen many answers talking about changing view sizes,etc... but none of them has worked nicely so far.

Could anybody clarify the "right" way to do this with a concrete code example?

Thanks in advance, Jonathan

+1  A: 

I ran into something like your problem (I wanted a screen similar to the iPhone's settings.app with a bunch of editable cells stacked on on top of another) and found that this approach worked well:

http://cocoawithlove.com/2008/10/sliding-uitextfields-around-to-avoid.html

drewh
Thanks, I've tried that but it's still quite buggy.I use the cell bounds instead of the text field bounds cause my cell contains multiple text fields.It works but after a while or a few manoeuvres on the different textfields suddenly the origin of my table is down a fourth of the screen... :(
Update - thanks again, this now worked. I just had to make a minor change by making sure I reset the origin of my view when the keyboard hides..
Update again - Did you get this to work for landscape mode? I get really wierd values on the height of my view in landscape mode and the calculations go wrong...
No, haven't done landscape mode yet, sorry.
drewh
Hi,Main problem seems to be that moving to landscape mode the coordinates are wrong because we use the window to convertRect.The changes I've made: calculate textFieldRect from the cell.bounds and set origin to cell.frame.origin.y.convertRect for viewRect from self.view and not self.view.window.
+1  A: 

Since you have textfields in a table, the best way really is to resize the table - you need to set the tableView.frame to be smaller in height by the size of the keyboard (I think around 165 pixels) and then expand it again when the keyboard is dismissed.

You can optionally also disable user interaction for the tableView at that time as well, if you do not want the user scrolling.

Kendall Helmstetter Gelner
I second this, and register for UIKeyboardWillShowNotification to find the size of the keyboard dynamically.
benzado
The number returned by the notification object doesn't work though. Or at least it didn't in 2.2, the number returned was incorrect and I had to hard-code the 165 value to adjust the height correctly (it was off by five to ten pixels)
Kendall Helmstetter Gelner
+21  A: 

I think I've come up with the solution to match the behaviour of Apple's apps.

First, in your viewWillAppear: subscribe to the keyboard notifications, so you know when the keyboard will show and hide, and the system will tell you the size of the keyboard, but dont' forget to unregister in your viewWillDisappear:.

[[NSNotificationCenter defaultCenter]
    addObserver:self
       selector:@selector(keyboardWillShow:)
           name:UIKeyboardWillShowNotification
         object:nil];
[[NSNotificationCenter defaultCenter]
    addObserver:self
       selector:@selector(keyboardWillHide:)
           name:UIKeyboardWillHideNotification
         object:nil];

Implement the methods similar to the below so that you adjust the size of your tableView to match the visible area once the keyboard shows. Here I'm tracking the state of the keyboard separately so I can choose when to set the tableView back to full height myself, since you get these notifications on every field change. Don't forget to implement keyboardWillHide: and choose somewhere appropriate to fix your tableView size.

-(void) keyboardWillShow:(NSNotification *)note
{
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
    keyboardHeight = keyboardBounds.size.height;
    if (keyboardIsShowing == NO)
    {
        keyboardIsShowing = YES;
        CGRect frame = self.view.frame;
        frame.size.height -= keyboardHeight;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3f];
        self.view.frame = frame;
        [UIView commitAnimations];
    }
}

Now here's the scrolling bit, we work out a few sizes first, then we see where we are in the visible area, and set the rect we want to scroll to to be either the half view above or below the middle of the text field based on where it is in the view. In this case, we have an array of UITextFields and an enum that keeps track of them, so multiplying the rowHeight by the row number gives us the actual offset of the frame within this outer view.

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    CGFloat rowHeight = self.tableView.rowHeight;
    if (textField == textFields[CELL_FIELD_ONE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_ONE;
    }
    else if (textField == textFields[CELL_FIELD_TWO])
    {
        frame.origin.y += rowHeight * CELL_FIELD_TWO;
    }
    else if (textField == textFields[CELL_FIELD_THREE])
    {
        frame.origin.y += rowHeight * CELL_FIELD_THREE;
    }
    else if (textField == textFields[CELL_FIELD_FOUR])
    {
        frame.origin.y += rowHeight * CELL_FIELD_FOUR;
    }
    CGFloat viewHeight = self.tableView.frame.size.height;
    CGFloat halfHeight = viewHeight / 2;
    CGFloat midpoint = frame.origin.y + (textField.frame.size.height / 2);
    if (midpoint < halfHeight)
    {
        frame.origin.y = 0;
        frame.size.height = midpoint;
    }
    else
    {
        frame.origin.y = midpoint;
        frame.size.height = midpoint;
    }
    [self.tableView scrollRectToVisible:frame animated:YES];
}

This seems to work quite nicely.

Michael Baltaks
Nice solution. Thanks for posting it.
Alex Reynolds
Its' not working on 4.0 any help ...
iPhoneDev
A: 

Hi,

what you meen in your code with "CELL_FIELD_ONE" ? Is this an integer: 0, 1 ,2 ,3...for ONE, TWO,...

frame.origin.y += rowHeight * CELL_FIELD_ONE;

thanks.

I've added an explanation for this in the answer.
Michael Baltaks
+5  A: 

The function that does the scrolling could be much simpler:

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    UITableViewCell *cell = (UITableViewCell*) [[textField superview] superview];
    [tView scrollToRowAtIndexPath:[tView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

That's it. No calculations at all.

I don't think that's going to match the Apple behaviour where the text field responder is centred within the visible area of the table view.
Michael Baltaks
And why not?! Just replace UITableViewScrollPositionTop with UITableViewScrollPositionMiddle. You just need to rescale the UITableView to adjust the visible area, of course.
MihaiD
Great suggestion.
Luther Baker
Very useful ! You can even make it more independant by getting the table view that way: UITableView *tView = (UITableView*) [cell superview];
John Riche
A: 

If you use a uitableview to place your textfields (from Jeff Lamarche), you can just scroll the tableview using the delegate method like so.

(Note: my text fields are stored in an array with the same index as there row in the tableview)

- (void) textFieldDidBeginEditing:(UITextField *)textField
    {

        int index;
        for(UITextField *aField in textFields){

            if (textField == aField){
                index = [textFields indexOfObject:aField]-1;
            }
        }

         if(index >= 0) 
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

        [super textFieldDidBeginEditing:textField];
    }
Corey Floyd
+3  A: 

Keyboard notifications work, but Apple's sample code for that assumes that the scroll view is the root view of the window. This is usually not the case. You have to compensate for tab bars, etc., to get the right offset.

It is easier than it sounds. Here is the code I use in a UITableViewController. It has two instance variables, hiddenRect and keyboardShown.

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
    if (keyboardShown)
        return;

    NSDictionary* info = [aNotification userInfo];

    // Get the frame of the keyboard.
    NSValue *centerValue = [info objectForKey:UIKeyboardCenterEndUserInfoKey];
    NSValue *boundsValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGPoint keyboardCenter = [centerValue CGPointValue];
    CGRect keyboardBounds = [boundsValue CGRectValue];
    CGPoint keyboardOrigin = CGPointMake(keyboardCenter.x - keyboardBounds.size.width / 2.0,
                                         keyboardCenter.y - keyboardBounds.size.height / 2.0);
    CGRect keyboardScreenFrame = { keyboardOrigin, keyboardBounds.size };


    // Resize the scroll view.
    UIScrollView *scrollView = (UIScrollView *) self.tableView;
    CGRect viewFrame = scrollView.frame;
    CGRect keyboardFrame = [scrollView.superview convertRect:keyboardScreenFrame fromView:nil];
    hiddenRect = CGRectIntersection(viewFrame, keyboardFrame);

    CGRect remainder, slice;
    CGRectDivide(viewFrame, &slice, &remainder, CGRectGetHeight(hiddenRect), CGRectMaxYEdge);
    scrollView.frame = remainder;

    // Scroll the active text field into view.
    CGRect textFieldRect = [/* selected cell */ frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];

    keyboardShown = YES;
}


// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
    // Reset the height of the scroll view to its original value
    UIScrollView *scrollView = (UIScrollView *) self.tableView;
    CGRect viewFrame = [scrollView frame];
    scrollView.frame = CGRectUnion(viewFrame, hiddenRect);

    keyboardShown = NO;
}
Dustin Voss
+2  A: 

A more stream-lined solution. It slips into the UITextField delegate methods, so it doesn't require messing w/ UIKeyboard notifications.

Implementation notes:

kSettingsRowHeight -- the height of a UITableViewCell.

offsetTarget and offsetThreshold are baed off of kSettingsRowHeight. If you use a different row height, set those values to point's y property. [alt: calculate the row offset in a different manner.]

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
CGFloat offsetTarget = 113.0f; // 3rd row
CGFloat offsetThreshold = 248.0f; // 6th row (i.e. 2nd-to-last row)

CGPoint point = [self.tableView convertPoint:CGPointZero fromView:textField];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

CGRect frame = self.tableView.frame;
if (point.y > offsetThreshold) {
 self.tableView.frame = CGRectMake(0.0f,
       offsetTarget - point.y + kSettingsRowHeight,
       frame.size.width,
       frame.size.height);
} else if (point.y > offsetTarget) {
 self.tableView.frame = CGRectMake(0.0f,
       offsetTarget - point.y,
       frame.size.width,
       frame.size.height);
} else {
 self.tableView.frame = CGRectMake(0.0f,
       0.0f,
       frame.size.width,
       frame.size.height);
}

[UIView commitAnimations];

return YES;

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

CGRect frame = self.tableView.frame;
self.tableView.frame = CGRectMake(0.0f,
      0.0f,
      frame.size.width,
      frame.size.height);

[UIView commitAnimations];

return YES;

}

Kelvin
+3  A: 

Hi

I'm doing something very similar it's generic, no need to compute something specific for your code. Just check the remarks on the code:

In MyUIViewController.h

@interface MyUIViewController: UIViewController <UITableViewDelegate, UITableViewDataSource>
{
     UITableView *myTableView;
     UITextField *actifText;
}

@property (nonatomic, retain) IBOutlet UITableView *myTableView;
@property (nonatomic, retain) IBOutlet UITextField *actifText;

- (IBAction)textFieldDidBeginEditing:(UITextField *)textField;
- (IBAction)textFieldDidEndEditing:(UITextField *)textField;

-(void) keyboardWillHide:(NSNotification *)note;
-(void) keyboardWillShow:(NSNotification *)note;

@end

In MyUIViewController.m

@implementation MyUIViewController

@synthesize myTableView;
@synthesize actifText;

- (void)viewDidLoad 
{
    // Register notification when the keyboard will be show
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(keyboardWillShow:)
                                          name:UIKeyboardWillShowNotification
                                          object:nil];

    // Register notification when the keyboard will be hide
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(keyboardWillHide:)
                                          name:UIKeyboardWillHideNotification
                                          object:nil];
}

// To be link with your TextField event "Editing Did Begin"
//  memoryze the current TextField
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.actifText = textField;
}

// To be link with your TextField event "Editing Did End"
//  release current TextField
- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    self.actifText = nil;
}

-(void) keyboardWillShow:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.myTableView.frame;

    // Start animation
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // Reduce size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height -= keyboardBounds.size.height;
    else 
        frame.size.height -= keyboardBounds.size.width;

    // Apply new size of table view
    self.myTableView.frame = frame;

    // Scroll the table view to see the TextField just above the keyboard
    if (self.actifText)
      {
        CGRect textFieldRect = [self.myTableView convertRect:self.actifText.bounds fromView:self.actifText];
        [self.myTableView scrollRectToVisible:textFieldRect animated:NO];
      }

    [UIView commitAnimations];
}

-(void) keyboardWillHide:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.myTableView.frame;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // Reduce size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height += keyboardBounds.size.height;
    else 
        frame.size.height += keyboardBounds.size.width;

    // Apply new size of table view
    self.myTableView.frame = frame;

    [UIView commitAnimations];
}

@end
ZeLegolas
using the notifications and getting the keyboard height while incorporating device orientation was awesome, thanks for that! the scrolling part did not work for me for some reason, so i had to use this: `[tableView scrollToRowAtIndexPath: indexPath atScrollPosition: UITableViewScrollPositionMiddle animated: YES];`
taber
This is the best answer here I think. Very clean. Only two things:1) your viewDidLoad is not calling [super viewDidLoad] and 2) I had to had in some tabbar math on the frame.size.height lines. Otherwise perfect! Thanks.
toxaq
Actually, another point, your whole viewDidLoad should actually be in your initWithNib methoed. Otherwise if you reuse the view the notifications will get registered more than once. Additionally, I needed to removed the tabbar height in the same way I added it if that wasn't obvious from my earlier comment.
toxaq
A: 

I like this last one. However, if you have a tab bar, this leaves a white area at the bottom of the scrolled view. I think the height of the tab bar should be substracted from the scroll distance (though I don't know how to do).

Mini-Stef
this should have been a comment, fyi! :)
taber
A: 

If you use UITableViewController instead of UIViewController, it will automatically do so.

Sam Ho
Don't provide such a spam answer for nothing. It wastes time of other people.
sfa
Did you try and found that not working? Or is the solution too simple for you to believe? Just extend the UITableViewController instead of UIViewController and the cell containing the textfields will scroll above the keyboard whenever the textfields become the first responder. No extra code needed.
Sam Ho
+1  A: 

If you use Three20, then use the autoresizesForKeyboard property. Just set in the your view controller's -initWithNibName:bundle method

self.autoresizesForKeyboard = YES

This takes care of:

  1. Listening for keyboard notifications and adjusting the table view's frame
  2. Scrolling to the first responder

Done and done.

Think Top Down
A: 

This works perfectly, and on iPad too.

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{

    if(textField == textfield1){
            [accountName1TextField becomeFirstResponder];
        }else if(textField == textfield2){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield3 becomeFirstResponder];

        }else if(textField == textfield3){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield4 becomeFirstResponder];

        }else if(textField == textfield4){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield5 becomeFirstResponder];

        }else if(textField == textfield5){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield6 becomeFirstResponder];

        }else if(textField == textfield6){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield7 becomeFirstResponder];

        }else if(textField == textfield7){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield8 becomeFirstResponder];

        }else if(textField == textfield8){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textfield9 becomeFirstResponder];

        }else if(textField == textfield9){
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            [textField resignFirstResponder];
        }
AWright4911