Dismiss keyboard of TextField programmatically

落花浮王杯 提交于 2019-12-25 02:23:03

问题


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];

}

回答1:


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];
}



回答2:


use this code in viewdidload

 UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.view addGestureRecognizer:gestureRecognizer];
  } 

 - (void) hideKeyboard 
  {
[textfieldname1 resignFirstResponder];
    [textfieldname2 resignFirstResponder];
  }



回答3:


Add UITextFieldDelegate to your header and implement this delegate method:

textFieldShouldEndEditing:

resign your first responder in the method.



来源:https://stackoverflow.com/questions/7912586/dismiss-keyboard-of-textfield-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!