[英]Dismiss keyboard of TextField programmatically
I know how to use the following method by Interface Builder. 我知道如何通过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 这是.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
{
UITextField *testTextField;
}
@property (nonatomic,retain) UITextField *testTextField;
@end
here's .m 这是.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];
}
What you lack is the UITextFieldDelegate
with it comes a lot of textfield methods that will be called for different reasons. 您缺少的是
UITextFieldDelegate
,它带有许多会因不同原因而调用的文本字段方法。
Check out the apple docs! 看看苹果文档! http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html
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];
}
use this code in viewdidload 在viewdidload中使用此代码
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.view addGestureRecognizer:gestureRecognizer];
}
- (void) hideKeyboard
{
[textfieldname1 resignFirstResponder];
[textfieldname2 resignFirstResponder];
}
Add UITextFieldDelegate
to your header and implement this delegate method: 将
UITextFieldDelegate
添加到标题中,并实现以下委托方法:
textFieldShouldEndEditing:
resign your first responder in the method. 在该方法中辞职第一响应者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.