Reputation: 12527
How can I hide the keyboard after the user presses 'Done', or taps the UITextField?
I have put this code in the AppDelegate:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
And I have linked the UITextField delegate in IB to the File's Owner..
What am I doing wrong?
EDIT: Changin return NO -> return YES does nothing. I have IB open and clicking on file's owner -> connections tab, there are multiple referencing outlets all pointing to the UITextfields. It still isn;t working..
UPDATE:
I added this to my function:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
int i = 5;
NSLog(@"%d", i);
return YES;
}
Nothing is getting printed to the console when I press return after setting focus to the textfield...So it's not calling the function. Have I connected something up incorrectly? I have the return key acting as 'Done'too, not sure if that makes a difference?
UPDATE:
I had my testfieldShouldReturn function in my AppDelegate instead of my viewcontroller. My mistake....Thanks for your help guys
Upvotes: 2
Views: 1867
Reputation: 5782
Hope this video tutorial will help you..
http://www.thenewboston.com/?p=1368&pOpen=tutorial
Call that textFieldShouldReturn function on return key Press to do this:
1) right click text field from where the key board pops up. 2) Select first option "Did end on exit". 3) Drag blue line to files owner and you will have an option to select "hideKeyboard" function option
And you are done.
Upvotes: 0
Reputation: 14073
Replace return NO;
with return YES;
.
This works in my code.
EDIT: I was wrong. The return value is not the problem here. The keyboard should hide when you call resignFirstResponder
.
Upvotes: 0
Reputation: 491
In your .h
-(IBAction)hideKeyboard:(id)sender;
In your .m or .mm
-(IBAction)hideKeyboard:(id)sender {
[(UITextField*)sender resignFirstResponder];
}
Then just link them in Interface builder to your text field's "Did End On Exit" event.
Upvotes: 0
Reputation: 5999
Your code looks good. Can you make sure that you do have the delegate connection set up correctly? Try adding an NSLog to the delegate method to see if it is even being called.
...
Your question update points to this definitely being a connection issue. Try what Vince suggests and set the delegate explicitly in code. You'll probably want to do this in the viewDidLoad method of your view controller to ensure that the textField has actually been loaded before you set its delegate. Post back about whether that works.
Upvotes: 1
Reputation:
Just set your app delegate as the delegate of your UITextField.
[textField setDelegate:self];
Set it in the -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
method of your app delegate.
Upvotes: 1
Reputation: 8001
Since you want the textfield to return. You should return YES;
instead of NO
.
Upvotes: 0