[英]Dismiss keyboard when user taps outside the textField
I'm trying to dismiss the keyboard when the user selects something other than the textFiled
. 当用户选择除
textFiled
之外的其他内容时,我试图关闭键盘。 I tried the following: 我尝试了以下方法:
- (void)viewDidLoad {
mytextField1.delegate = self;
mytextFiled2.delegate = self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
This didn't work. 这没用。 I then tried
[... resignFirstResponder]
in touchesBagan
, and that didn't work either. 然后,我在
touchesBagan
尝试了[... resignFirstResponder]
,但该方法也不起作用。 Am I doing something wrong? 难道我做错了什么? Why is this not working?
为什么这不起作用?
您是否尝试过在文本字段的超级视图上添加UITapGestureRecognizer以关闭键盘?
Add a tap gesture to the view (not the text field) so that you know when someone taps the view. 向视图(而不是文本字段)添加轻击手势,以便您知道某人何时单击视图。
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
[self.view addGestureRecognizer:tap];
Then when that method is called, resign first responder to dismiss the keyboard. 然后,在调用该方法时,请辞职第一响应者以退出键盘。
- (void)viewTapped
{
if (self.textField.isFirstResponder) {
[self.textField resignFirstResponder];
}
}
You can use UITapGestureRecognizer. 您可以使用UITapGestureRecognizer。 And also save the current focused TextField at activeTF.
并将当前已聚焦的TextField保存在activeTF中。 You need to set the current view controller as the delegate of UITextField(s).
您需要将当前视图控制器设置为UITextField的委托。
UITextField *activeTF;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
.......
UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:dismissTap];
}
- (void)dismissKeyboard {
if (activeTF) {
[activeTF resignFirstResponder];
}
}
#pragma mark - TextField Delegate
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
activeTF = sender;
}
- (void)textFieldDidEndEditing:(UITextField *)sender
{
activeTF = nil;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.