Search code examples
objective-ciosxcodesetfocusresignfirstresponder

Xcode - setFocus on a text field, becomeFirstResponder isn't enough


At the moment, I trigger a method on 'Did End On Exit' in my app (I'm aware that this may not be the greatest way of doing it but I'm very new to Objective C and Xcode for that matter and I'm simply doing what feels comfortable to me).

This method resigns the firstResponder from the current text field and applies it to a later text field.

The problem I'm facing is that the keyboard covers the next text field so that the use has no idea where the focus is and therefore what they are required to type.

How do I get it so that my keyboard shifts down and actually shows the text box that is currently active? Making something the firstResponder simply doesn't do what I want it to, unless there's part of the implementation I'm missing.

Here's my simple method:

- (IBAction)firstNameNext:(id)sender {
[firstNameTextField resignFirstResponder];
[surnameTextField becomeFirstResponder];
}

Any advice would be super.


Solution

  • Add UIScrollView in your main view then all contents as subview to UIScrollView

    Now when specific UITextField needs to be able to visible in view use its delegate like this:

    Note: add UITextFieldDelegate in .h file like this

    @interface yourViewController : UIViewController<UITextFieldDelegate>
    

    Also bind with File's Owner

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;
    {
       if(textField == yourSpecficTextField) //one u want move upwards
       {
          yourScrollView.contentOffset = CGPointMake(0,200); //required offset
       }
       ... //provide contentOffSet those who needed
       return YES;
    }
    
    - (void)textFieldDidEndEditing:(UITextField *)textField
    {
       yourScrollView.contentOffset = CGPointMake(0,0); //make UIScrollView as it was before
    }