We can be achieved in 4 steps.
- Set ViewController as delegate of UITextField
- Adopt UITextFieldDelegate Protocol
- Get a message of return key from UITextField
- Hide the keyboard
1. Set ViewController as delegate of UITextField
UITextField object sends a message for its delegate when user taps the return key. First, we set VewController as the delegate.
Please open Xcode, and click a storyboard file. And drag from UITextField to ViewController while holding down the control key. There is a blue line on screen while you holding down the control key.
Click "delegate" from pop up menu.
OK. It's done. You can look see the connection of delegate on Utilities pane.
2. Adopt UITextFieldDelegate Protocol
UITextField and its delegate communicate each other with UITextFieldDelegate Protocol. Adopt UITextFieldDelegate protocol to ViewController by writing following code.
#import <UIKit/UIKit.h> @interface TaskViewController : UIViewController <UITextFieldDelegate> @endUIViewController declared that is adopting UITextFieldDelegateProtocol itself.
3. Get a message of return key from UITextField
UITextField sends "textfieldShouldReturn:" message to its delegate when user taps the return key. Now, implement to this method to confirmation whether a message has actually arrived. Edit ViewController as below.
xxxxViewController.h
xxxxViewController.m
xxxxViewController.h
#import <UIKit/UIKit.h> @interface TaskViewController : UIViewController <UITextFieldDelegate>// ADD HERE - (BOOL)textFieldShouldReturn:(UITextField *)textField; @end
xxxxViewController.m
#import "TaskViewController.h" @interface TaskViewController () @end @implementation TaskViewController // ADD HERE -(BOOL)textFieldShouldReturn:(UITextField *)textField { NSLog(@"tapped return key!"); return YES; } - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end
Run this code, and tap UITextField. When you tap the return key, log is output in debug area.
4. Hide the keyboard
Finally, add the process of hiding the keyboard. Edit textFieldShouldReturn: method as below.
-(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; }
If we want to hide the keyboard, send resignFirstResponder: message to the keyboard object.
No comments:
Post a Comment