Reputation: 42069
I got the code below from this SO question. I'm trying to slide up textfields when I begin editing (because they otherwise get covered by the iPhone keyboard). However, the log statement reveals that the textFieldDidBeginEditing method is not getting called.
I have the code below in two different subclasses of UIViewController. In one of them, for example, I have a textfield connected from the storyboard to the UIViewController like this
@property (strong, nonatomic) IBOutlet UITextField *mnemonicField;
I moved the textfield up to the top of the view (i.e. not covered by keyboard) so that I could edit it to try to trigger the log statement but it didn't work. The text field otherwise works as expected i.e. the data I enter is getting saved to coreData etc etc.
Can you explain what I might be doing wrong?
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(@"The did begin edit method was called");
[self animateTextField: textField up: YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField: textField up: NO];
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
const int movementDistance = 180; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}
Upvotes: 16
Views: 22066
Reputation: 1133
In other case if you click any other button without moving the focus of Uitextfield then delegate will not be called, for that you need to explicitly call
yourtextfield.resignFirstResponder()
Upvotes: 1
Reputation: 1108
You created IBOutlet so just drag your textfield to viewController and set delegate
Then in .h add the following
@interface ViewController : ViewController<UITextFieldDelegate>
Upvotes: 4
Reputation: 25459
You should set up text field delegate to self. Add this line to viewDidLoad method:
self.mnemonicField.delegate = self;
and remember to add this line <UITextFieldDelegate>
to conform to that protocol.
You can achieve the same effect in storyboard by control drag from desired UITextField to view controller and select delegate.
Upvotes: 4
Reputation: 3506
You have not assigned your delegate
of UITextField
in your ViewController
class:
In your viewcontroller.m file, In ViewDidLoad
method, do this:
self.mnemonicField.delegate=self;
In your viewcontroller.h file, do this:
@interface YourViewController : ViewController<UITextFieldDelegate>
Upvotes: 43