0

I know how to use the following method by Interface Builder.

-(void)dismissKeyboard { [testTextField resignFirstResponder]; } 

In this way, when I touch the area outside the keyboard or tap the "return", the keyboard will dismiss.

But I don't know how to make it all by code. Please teach me , thanks.

Here's .h

#import <UIKit/UIKit.h> @interface SecondViewController : UIViewController { UITextField *testTextField; } @property (nonatomic,retain) UITextField *testTextField; @end 

here's .m

#import "SecondViewController.h" @implementation SecondViewController @synthesize testTextField; - (void)viewDidLoad { [super viewDidLoad]; UITextField *tempTextField = [[UITextField alloc] init]; self.testTextField = tempTextField; testTextField.frame = CGRectMake(100, 150, 200, 30); testTextField.placeholder = @"Test"; testTextField.backgroundColor = [UIColor whiteColor]; testTextField.textColor = [UIColor blackColor]; [self.view addSubview:testTextField]; } 
2
  • You didn't set the delegate.. [tempTextField setDelegate:self]; Commented Feb 29, 2012 at 2:43
  • @DefenestrationDay yours is the right answer! Commented Nov 5, 2012 at 2:54

3 Answers 3

3

What you lack is the UITextFieldDelegate with it comes a lot of textfield methods that will be called for different reasons.

Check out the apple docs! http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

You should resign your keyboard in the

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField { [textField resignFirstResponder]; } 
Sign up to request clarification or add additional context in comments.

Comments

3

use this code in viewdidload

 UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)]; [self.view addGestureRecognizer:gestureRecognizer]; } - (void) hideKeyboard { [textfieldname1 resignFirstResponder]; [textfieldname2 resignFirstResponder]; } 

Comments

0

Add UITextFieldDelegate to your header and implement this delegate method:

textFieldShouldEndEditing: 

resign your first responder in the method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.