views:

336

answers:

3

I understand that this problem is incredibly common and I have read through quite a few answers but am having trouble understanding how the code works. This works:

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
if ([sender isEqual:txtLeaveAddyLine1])
{
    //move the main view, so that the keyboard does not hide it.
    if  (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
} 
}

In this example, txtLeaveAddy is the very first UITextField that is hidden by the keyboard and it works like a charm. As I cycle through the text fields on the screen it scrolls up when the user enters into that txtLeaveAddyLine1 field. However, when I try to add the fields below the txtLeaveAddyLine1 field - nothing happens. For example:

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if ([sender isEqual:txtLeaveAddyLine1])
    {
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
    } 
    if ([sender isEqual:txtLeaveAddyLine2])
    {
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
    } 
}

Am I not using this function correctly?

A: 

setViewMovedUp is not a built in - its code from an Apple sample I think. (If you have a version different to the one I found the following may not apply...)

It doesn't magically move to the correct place, it just moves the view a fixed amount. I guess you need to look at that function and figure out how far you need the view to move for each field, and then modify the view to change the amount by which you move the view depending on the field location. Either hardwire something simple with a select case statement, or pass in the sender and look at its frame to figure out where to move the view to.

Andiih
see Robs own answer below - seems to cover it perfectly.
Andiih
+1  A: 

A common way to do this is have your text fields in a table view. When the text field begins editing, get the index path to the cell it's in and call:

[tableView scrollToRowAtIndexPath:indexPath 
                 atScrollPosition:UITableViewScrollPositionMiddle 
                         animated:YES];
Bruce Geerdes
How do you set up UITextFields and Labels in a table view? Each time I try to place a textfield or label over the table view it is really difficult - it doesnt want to allow me to put it in certain places.
Rob
Create a custom UITableViewCell with a label and text field. Then use that cell to populate the table.
Bruce Geerdes