我想知道如何使键盘消失时,用户触摸以外的UITextField。


当前回答

看看这个,这是最简单的方法,

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

Or

这个库将处理包括滚动条自动滚动,点击空间隐藏键盘等…

https://github.com/michaeltyson/TPKeyboardAvoiding

其他回答

我认为最简单(最好)的方法是子类化全局视图,并使用hitTest:withEvent方法来监听任何触摸。键盘上的触摸没有注册,所以hitTest:withEvent只在你触摸/滚动/滑动/捏…然后调用[self - ending:YES]。

这比使用touchesBegan要好,因为如果你点击视图顶部的按钮,touchesBegan不会被调用。它比无法识别滚动手势的UITapGestureRecognizer更好。它也比使用暗屏更好,因为在复杂和动态的用户界面中,你不能到处都放暗屏。此外,它不会阻止其他动作,你不需要点击两次来选择外面的按钮(就像在UIPopover的情况下)。

此外,这比调用[textField resignFirstResponder]更好,因为你可能在屏幕上有许多文本字段,所以这适用于所有的文本字段。

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

- (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];
            }
        } 
    }
}

在viewDidLoad 斯威夫特4.2 代码是这样的

let viewTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(dismissKeyboard))
        view.addGestureRecognizer(viewTap)
@objc func dismissKeyboard() {
        view.endEditing(true)
    }

在这种情况下,可以使用ScrollView,并添加到文本字段在ScrollView和我想点击ScrollView和视图,然后解散键盘。为了以防万一,我尝试创建了示例代码。像这样,

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tap(_:)))
        view.addGestureRecognizer(tapGesture)
        // Do any additional setup after loading the view, typically from a nib.
    }
    func tap(gesture: UITapGestureRecognizer) {
        textField.resignFirstResponder()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

你的故事板看,就像。

对于那些在Swift中挣扎的人。这是Jensen2k在Swift中接受的答案。

斯威夫特2.3

    override func viewDidLoad() {
        //.....

        let viewTapGestureRec = UITapGestureRecognizer(target: self, action: #selector(handleViewTap(_:)))
        //this line is important
        viewTapGestureRec.cancelsTouchesInView = false
        self.view.addGestureRecognizer(viewTapGestureRec)

         //.....
    }

    func handleViewTap(recognizer: UIGestureRecognizer) {
        myTextField.resignFirstResponder()
    }