我想知道如何让键盘消失,当用户触摸外面的UITextField。
检查一下,这将是最简单的方法来做到这一点,
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];// this will do the trick
}
要么
这个库将处理包括滚动条自动滚动,点击空间隐藏键盘等...
https://github.com/michaeltyson/TPKeyboardAvoiding
找到了一些答案。
使用在viewDidLoad期间被初始化:
UIGestureRecognizer *tapper;
- (void)viewDidLoad
{
[super viewDidLoad];
tapper = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSingleTap:)];
tapper.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapper];
}
关闭正在编辑的内容:
- (void)handleSingleTap:(UITapGestureRecognizer *) sende
{
[self.view endEditing:YES];
}
你需要添加一个UITapGestureRecogniser并将其分配给视图,然后UITextField在其选择器上调用resign first responder 。
代码:
在viewDidLoad中
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
在关闭键盘:
-(void)dismissKeyboard
{
[aTextField resignFirstResponder];
}
(哪里aTextField是负责键盘的文本字段)
Swift 3版本看起来像这样
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)
对于dismissKeyboard
func dismissKeyboard (_ sender: UITapGestureRecognizer) {
aTextField.resignFirstResponder()
}
相似问题