My UIButton is set to disappear every time my UITextField is done editing, I invoke the textFieldDidEndEditing: method, and just have the button fade away. This works fine, unless I switch to another textfield without clicking out of the first one. So for instance, I’m on textfield A, and just tap textfield B, the keyboard still stays up, and so does the button. I don’t believe that there is a method that covers textfields switching like this, only when ALL the textfields are done editing. Am I wrong? Here is my code:
-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField
{
negButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
negButton.frame = CGRectMake(textField.frame.origin.x, textField.frame.origin.y, 37, textField.frame.size.height);
[negButton setAlpha:0];
return YES;
}
-(void) textFieldDidBeginEditing:(UITextField *)textField
{
if ([textField isEditing])
{
[UIView animateWithDuration:0.3 animations:^
{
field = textField;
CGRect frame = textField.frame;
frame.size.width -= 40;
frame.origin.x += 40;
[negButton setAlpha:1];
[textField setFrame:frame];
[self.view addSubview:negButton];
}];
}
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
[UIView animateWithDuration:0.3 animations:^
{
CGRect frame = textField.frame;
frame.size.width += 40;
frame.origin.x -= 40;
[negButton setAlpha:0];
[textField setFrame:frame];
}
];
}
The problem here is the order that your delegate methods are being called.
Let’s say that you are going from textField1 to textField2.
Once textField1 is already active and you click on textField2, they get called like this:
You are creating your new
negButtonintextFieldShouldBeginEditingwhich over-writes the reference to the “old” button (beside textField1) by creating one beside textField2 and storing it’s reference instead. Next, you calltextFieldDidEndEditingandtextFieldDidBeginEditingon the new button.What you want to do is move your code that is currently in
textFieldShouldBeginEditingto the beginning oftextFieldDidBeginEditingso that the previous two methods act upon the appropriate button before the new one is created.