检测点击何时在 UITextView 之外

Detect when taps are outside of a UITextView

我正在开发一个包含各种 UITextView 的程序。我遇到的问题是我无法检测到用户何时在 UITextView 之外点击,以便我可以隐藏键盘。我尝试了各种操作,但其中 none 行得通。

我在操作中使用的代码:

@IBAction func touchOutsideTextField(sender: UITextField)
{
    sender.resignFirstResponder()
}

我应该怎么做才能隐藏键盘而不是这个?

你可以使用UITapGestureRecognizer

将 TapGesture 添加到 View 中,当点击 View 时键盘将隐藏。

这是适合您的示例代码。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var text: UITextView!
@IBOutlet weak var text2: UITextView!
@IBOutlet weak var text3: UITextView!
@IBOutlet weak var text4: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    let aSelector : Selector = "touchOutsideTextField"
    let tapGesture = UITapGestureRecognizer(target: self, action: aSelector)
    tapGesture.numberOfTapsRequired = 1
    view.addGestureRecognizer(tapGesture)
}

func touchOutsideTextField(){

    self.view.endEditing(true)

    }

}

或者您可以使用 touchesBegan 方法添加此代码,如果您想尝试这种方式。

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    self.view.endEditing(true)
}

使用此代码,您无需添加 UITapGestureRecognizer

您可以选择其中一项。

对于那些仍在使用 Obj C 的人,这里是翻译:

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:TRUE];
}

Apple 在他们的文档中说,如果您省略对 super 的调用,那么您还必须重写其他触摸方法...即使您不使用它们。有关更多信息,请参见 link:touchesBegan:withEvent: