iOS - 在 UITextField 之外触摸时关闭键盘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5306240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:13:59  来源:igfitidea点击:

iOS - Dismiss keyboard when touching outside of UITextField

ioscocoa-touchuitextfielduikit

提问by jonepatr

I'm wondering how to make the keyboard disappear when the user touches outside of a UITextField.

我想知道当用户触摸UITextField.

回答by Jensen2k

You'll need to add an UITapGestureRecogniserand assign it to the view, and then call resign first responder on the UITextFieldon it's selector.

您需要添加一个UITapGestureRecogniser并将其分配给视图,然后UITextField在其选择器上调用 resign first responder 。

The code:

编码:

In viewDidLoad

在视图中加载

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];

[self.view addGestureRecognizer:tap];

In dismissKeyboard:

在解雇键盘中:

-(void)dismissKeyboard 
{
    [aTextField resignFirstResponder];
}

(Where aTextFieldis the textfield that is responsible for the keyboard)

aTextField负责键盘的textfield在哪里)

Swift 3version looks like that

Swift 3版本看起来像那样

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)

For dismissKeyboard

对于解雇键盘

func dismissKeyboard (_ sender: UITapGestureRecognizer) {
    aTextField.resignFirstResponder()
}

回答by drewish

I mashed up a few answers.

我混搭了几个答案。

Use an ivar that gets initialized during viewDidLoad:

使用在期间初始化的 ivar viewDidLoad:

UIGestureRecognizer *tapper;

- (void)viewDidLoad
{
    [super viewDidLoad];
    tapper = [[UITapGestureRecognizer alloc]
                initWithTarget:self action:@selector(handleSingleTap:)];
    tapper.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapper];
}

Dismiss what ever is currently editing:

关闭当前正在编辑的内容:

- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
    [self.view endEditing:YES];
}

回答by Prasad De Zoysa

Check this, this would be the easiest way to do that,

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

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

Or

或者

This library will handle including scrollbar auto scrolling, tap space to hide the keyboard, etc...

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

https://github.com/michaeltyson/TPKeyboardAvoiding

https://github.com/michaeltyson/TPKeyboardAvoiding

回答by Qiao Yi

I see that some people are having issues using the UITapGestureRecognizermethod. The easiest way that I've accomplished this functionality while still leaving my existing button's tap behavior intact is adding only one line to @Jensen2k 's answer:

我看到有些人在使用该UITapGestureRecognizer方法时遇到问题。我在保持现有按钮的点击行为不变的情况下完成此功能的最简单方法是仅在@Jensen2k 的答案中添加一行:

[tap setCancelsTouchesInView:NO];

This allowed my existing buttons to still work without using @Dmitry Sitnikov 's method.

这允许我现有的按钮在不使用 @Dmitry Sitnikov 的方法的情况下仍然可以工作。

Read about that propertyhere (search for CancelsTouchesInView): UIGestureRecognizer Class Reference

property在这里阅读(搜索CancelsTouchesInView):UIGestureRecognizer Class Reference

I'm not sure how it would work with scrollbars, as I see some had issues with, but hopefully someone else might run into the same scenario I had.

我不确定它如何与滚动条一起工作,因为我看到一些有问题,但希望其他人可能会遇到与我相同的情况。

回答by Dmitry Sitnikov

It is better to make your UIViewan instance of UIControl(in interface builder) and then connect their TouchUpInsideevent to dismissKeyboardmethod. This IBActionmethod will look like:

最好创建UIView一个UIControl(在界面构建器中)的实例,然后将它们的TouchUpInside事件连接到dismissKeyboard方法。这个IBAction方法看起来像:

- (IBAction)dismissKeyboard:(id)sender {
    [aTextBox resignFirstResponder];
}

回答by FBente

Swift 4

斯威夫特 4

Setup your UIViewControllerwith this extension method once e.g in viewDidLoad:

设置你的UIViewController这种扩展方法一旦如viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    self.setupHideKeyboardOnTap()
}

and the keyboard will be dismissed even by tapping on the NavigationBar.

即使点击 ,键盘也会被关闭NavigationBar

import UIKit
extension UIViewController {
    /// Call this once to dismiss open keyboards by tapping anywhere in the view controller
    func setupHideKeyboardOnTap() {
        self.view.addGestureRecognizer(self.endEditingRecognizer())
        self.navigationController?.navigationBar.addGestureRecognizer(self.endEditingRecognizer())
    }

    /// Dismisses the keyboard from self.view
    private func endEditingRecognizer() -> UIGestureRecognizer {
        let tap = UITapGestureRecognizer(target: self.view, action: #selector(self.view.endEditing(_:)))
        tap.cancelsTouchesInView = false
        return tap
    }
}

回答by Rob

Swift version, this works in combination with other elements (like a UIButtonor another UITextField):

Swift 版本,这与其他元素(如 aUIButton或 another UITextField)结合使用:

override func viewDidLoad() {
    super.viewDidLoad()

    let tapper = UITapGestureRecognizer(target: self, action:#selector(endEditing))
    tapper.cancelsTouchesInView = false
    view.addGestureRecognizer(tapper)
}

回答by Mr H

How about this: I know this is an old post. It might help someone :)

怎么样:我知道这是一个旧帖子。它可能会帮助某人:)

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {  
    NSArray *subviews = [self.view subviews];
    for (id objects in subviews) {
        if ([objects isKindOfClass:[UITextField class]]) {
            UITextField *theTextField = objects;
            if ([objects isFirstResponder]) {
                [theTextField resignFirstResponder];
            }
        } 
    }
}

回答by eduludi

This is a good generic solution:

这是一个很好的通用解决方案:

Objective-C:

目标-C:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];    
}

Swift:

迅速:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

Based on @icodebuster solution: https://stackoverflow.com/a/18756253/417652

基于@icodebuster 解决方案:https://stackoverflow.com/a/18756253/417652

回答by newDeveloper

Swift 4 oneliner

斯威夫特 4 单线

view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:))))