Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Focus Change for UITextField

I'm trying to set the animation for the view to move up when keyboard is hiding and appearing for the text fields and I got it to work perfectly fine, but when the focus moves from one text field to another, it doesn't work since the keyboard was already shown.

In viewDidLoad, I registered the following:

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

and then in the keyboardWillShow and keyboardWillHide methods, it determines if the view should move or not and animate accordingly. But if a keyboard was already shown and the user clicks on another text field that needs the view to move up, the method wouldn't get called. Is there any way to detect if a focus has been changed to another text field when the keyboard was already shown? It would be great if there is a way to do this without having to set all the text fields to delegates.

Thanks in advance.

like image 486
Dennis Avatar asked May 20 '12 07:05

Dennis


3 Answers

Use the UITextField delegate methods .. its better on your case than the keyboard methods .. when textField got focus the - (void)textFieldDidBeginEditing:(UITextField *)textField; will be fired .. and when it lost focus - (void)textFieldDidEndEditing:(UITextField *)textField; will be fired.

like image 74
Malek_Jundi Avatar answered Oct 23 '22 12:10

Malek_Jundi


-(BOOL)textFieldShouldBeginEditing:(UITextField*)textField {
if (textField.tag == 1) { //first textField tag
    //textField 1
}
else {
   //textField 2
}
}
like image 20
Warif Akhand Rishi Avatar answered Oct 23 '22 10:10

Warif Akhand Rishi


Use UITextFieldDelegate

and

func textFieldDidBeginEditing(textField: UITextField) {
        println("did")
        if textField.tag == 1{
            self.txtFullName.layer.borderColor = UIColor.blueColor().CGColor
        }
    }
like image 8
Raymond Led Carasco Avatar answered Oct 23 '22 11:10

Raymond Led Carasco