Pages

Monday 26 August 2013

Hiding keyboard on pressing return key in iOS

10 month ago when I start iOS programing this was a confusing task for me to hide keyboard on pressing return key. Hiding keyboard by taping background was much more confusing, but actually these two tasks are very easy So today we will learn both of these.

I am assuming that you have created a single view application in xCode.

Hide keyboard by pressing return key.

1- Make  the screen like this.




2- Go to .h file and implement UITextFieldDelegate protocol like this.



#import 

@interface ViewController : UIViewController<UITextFieldDelegate>

@end

 }

3- Now make the property for text field(if you know ho to make property then go to step 4).
 Open assistant editor and press ctr + left click and drop at .h file like below.

A new small window will be opened like this.






Give name in the name box. After this a property will be made and .h file look like this.



4-  Now to go to .m file and set the delegate of text field.



- (void)viewDidLoad
{
    [super viewDidLoad];
 
    self.textField.delegate=self;
}

5- Now finally implement the textFieldShouldReturn method like this.


-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


Now run the app and write something in text field then press return key it will work fine.
If you want to do same with other text field then just make property of text field and set delegate just, it will work.

I hope this post will help you, any comments good or b ad are always welcome. you can also request me for a tutorial.