在触摸UITextField外部时关闭键盘

我想知道如何在用户触摸到UITextField之外时使键盘消失。


您需要添加一个UITapGestureRecogniser并将其分配给该视图,然后在其选择器上调用UITextField上的第一响应者。

代码:

在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()
}

我找到了几个答案。

使用在viewDidLoad:期间初始化的伊娃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 *) sender
{
    [self.view endEditing:YES];
}

检查一下,这将是最简单的方法,

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
      [self.view endEditing:YES];// this will do the trick
}

要么

该库将处理包括滚动条自动滚动,点击空间以隐藏键盘等。

https://github.com/michaeltyson/TPKeyboardAvoiding

链接地址: http://www.djcxy.com/p/44221.html

上一篇: Dismiss keyboard when touching outside of UITextField

下一篇: Can I force a UITableView to hide the separator between empty cells?