通过触摸任何地方使用SwiftclosuresiOS键盘

我一直在寻找这个,但我似乎无法find它。 我知道如何解雇使用Objective-C的键盘,但我不知道如何使用Swift做到这一点? 有人知道吗?

 override func viewDidLoad() { super.viewDidLoad() //Looks for single or multiple taps. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") //Uncomment the line below if you want the tap not not interfere and cancel other interactions. //tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } //Calls this function when the tap is recognized. func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } 

================================================== ======================

编辑:这是另一种方法来做这个任务,如果你要在多个UIViewControllers中使用这个function:

 // Put this piece of code anywhere you like extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } } 

现在在每个UIViewController中,你所要做的就是调用这个函数:

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

这个函数是作为一个标准function包含在我的回购中,其中包含了很多有用的Swift扩展,请查看: https : //github.com/goktugyil/EZSwiftExtensions

一个关于如何使用下面的Swift在Xcode 6.1中closures键盘的问题的答案:

 import UIKit class ItemViewController: UIViewController, UITextFieldDelegate { @IBOutlet var textFieldItemName: UITextField! @IBOutlet var textFieldQt: UITextField! @IBOutlet var textFieldMoreInfo: UITextField! override func viewDidLoad() { super.viewDidLoad() textFieldItemName.delegate = self textFieldQt.delegate = self textFieldMoreInfo.delegate = self } ... /** * Called when 'return' key pressed. return NO to ignore. */ func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } /** * Called when the user click on the view (outside the UITextField). */ override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } } 

( 这个信息的来源 )。

你可以打电话

 resignFirstResponder() 

在UIResponder的任何实例上,例如UITextField。 如果您在当前导致键盘显示的视图上调用该键盘,那么键盘将会消失。

 //Simple exercise to demonstrate, assuming the view controller has a //Textfield, Button and a Label. And that the label should display the //userinputs when button clicked. And if you want the keyboard to disappear //when clicken anywhere on the screen + upon clicking Return key in the //keyboard. Dont forget to add "UITextFieldDelegate" and //"self.userInput.delegate = self" as below import UIKit class ViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var userInput: UITextField! @IBAction func transferBtn(sender: AnyObject) { display.text = userInput.text } @IBOutlet weak var display: UILabel! override func viewDidLoad() { super.viewDidLoad() //This is important for the textFieldShouldReturn function, conforming to textfieldDelegate and setting it to self self.userInput.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //This is for the keyboard to GO AWAYY !! when user clicks anywhere on the view override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } //This is for the keyboard to GO AWAYY !! when user clicks "Return" key on the keyboard func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } 

对于Swift 3来说,这非常简单

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } 

如果你想按下RETURN键隐藏键盘

 func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } 

但在第二种情况下,您还需要将所有文本字段的委托传递给Main.Storyboard中的ViewController

Dash的答案是正确的,首选。 更“焦土”的方法是调用view.endEditing(true) 。 这会导致view及其所有子视图resignFirstResponder 。 如果您没有提及您想要取消的观点,这是一个有效的解决scheme。

请注意,我个人认为您应该参考您希望辞职的急救人员。 .endEditing(force: Bool)是一个野蛮的方法; 请不要使用它。

在故事板中:

  1. selectTableView
  2. 从右侧select属性检查器
  3. 在键盘部分 – select你想要的退出模式

Swift 3:最简单的方法来closures键盘:

  //Dismiss keyboard method func keyboardDismiss() { textField.resignFirstResponder() } //ADD Gesture Recignizer to Dismiss keyboard then view tapped @IBAction func viewTapped(_ sender: AnyObject) { keyboardDismiss() } //Dismiss keyboard using Return Key (Done) Button //Do not forgot to add protocol UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { keyboardDismiss() return true } 

![如何禁用键盘..] [1]

 import UIKit class ViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! override func viewDidLoad() { super.viewDidLoad() username.delegate = self password.delegate = self // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore. { textField.resignFirstResponder() return true; } override func touchesBegan(_: Set<UITouch>, with: UIEvent?) { username.resignFirstResponder() password.resignFirstResponder() self.view.endEditing(true) } } 

Swift 3:

使用Selector作为参数的扩展,可以在dismiss函数中执行额外的工作,并取消cancelsTouchesInView以防止与视图的其他元素相关的失真。

 extension UIViewController { func hideKeyboardOnTap(_ selector: Selector) { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } } 

用法:

 override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardOnTap(#selector(self.dismissKeyboard)) } func dismissKeyboard() { view.endEditing(true) // do aditional stuff } 

这一个class轮辞去所有UITextField在UIView的所有(任何)的键盘

 self.view.endEditing(true) 

我发现最好的解决scheme包括@Esqarrouth接受的答案,并做了一些调整:

 extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboardView") tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } func dismissKeyboardView() { view.endEditing(true) } } 

tap.cancelsTouchesInView = false这一行非常重要:它确保UITapGestureRecognizer不会阻止视图上的其他元素接收用户交互。

方法dismissKeyboard()被更改为稍微不太优雅的dismissKeyboardView() 。 这是因为在我的项目的相当老的代码库中,有很多次dismissKeyboard()已经被使用(我想这不是罕见的),导致编译器问题。

然后,如上所述,可以在单独的视图控制器中启用此行为:

 override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() } 
  import UIKit class ItemViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var nameTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() self.nameTextField.delegate = self } // Called when 'return' key pressed. return NO to ignore. func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // Called when the user click on the view (outside the UITextField). override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } } 

您还可以添加轻击手势识别器来退出键盘。 :d

 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let recognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:")) backgroundView.addGestureRecognizer(recognizer) } func handleTap(recognizer: UITapGestureRecognizer) { textField.resignFirstResponder() textFieldtwo.resignFirstResponder() textFieldthree.resignFirstResponder() println("tappped") } 

另一种可能是简单地添加一个没有内容的大button,它位于您可能需要触摸的所有视图的下面。 给它一个名为:

 @IBAction func dismissKeyboardButton(sender: AnyObject) { view.endEditing(true) } 

手势识别器的问题对我来说,它也抓住了我想要通过tableViewCells接收的所有触摸。

作为一个新手程序员,当人们产生更多的技巧和不必要的回应时,可能会引起混淆……你不必做任何上面显示的复杂东西!

这里是最简单的select…如果你的键盘出现在响应文本字段 – 在你的触摸屏function,只需添加resignFirstResponder函数。 如下所示 – 因为First Responder被释放(退出响应者链),键盘将closures…

 override func touchesBegan(_: Set<UITouch>, with: UIEvent?){ MyTextField.resignFirstResponder() } 

如果你使用滚动视图,它可以更简单。

只需select故事板中的Dismiss interactively

Swift 3

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } 

当视图中有多个文本字段时

要遵循@modocache的build议 ,避免调用view.endEditing() ,你可以跟踪成为第一响应者的文本字段,但这是混乱和容易出错的。

另一种方法是在viewcontroller中的所有文本字段上调用resignFirstResponder() 。 下面是创build所有文本字段的集合的示例(在我的情况下,无论如何都需要validation代码):

 @IBOutlet weak var firstName: UITextField! @IBOutlet weak var lastName: UITextField! @IBOutlet weak var email: UITextField! var allTextFields: Array<UITextField>! // Forced unwrapping so it must be initialized in viewDidLoad override func viewDidLoad() { super.viewDidLoad() self.allTextFields = [self.firstName, self.lastName, self.email] } 

有了这个集合,迭代遍历它们是一件简单的事情:

 private func dismissKeyboard() { for textField in allTextFields { textField.resignFirstResponder() } } 

所以现在你可以在你的手势识别器(或适合你的任何地方dismissKeyboard()中调用dismissKeyboard() )。 缺点是在添加或删除字段时必须维护UITextField的列表。

评论欢迎。 如果在不是第一响应者的控件上调用resignFirstResponder()方法时遇到问题,或者有一个简单且有保证的无法跟踪当前第一响应者的方法,那么我很乐意听到!

我在uisearchbar上工作。 看我的。

 import UIKit class BidderPage: UIViewController,UISearchBarDelegate,UITableViewDataSource { let recognizer = UITapGestureRecognizer() // Set recogniser as public in case of tableview and didselectindexpath. func searchBarTextDidBeginEditing(searchBar: UISearchBar) { recognizer.addTarget(self, action: "handleTap:") view.addGestureRecognizer(recognizer) } func handleTap(recognizer: UITapGestureRecognizer) { biddersearchbar .resignFirstResponder() } func searchBarTextDidEndEditing(searchBar: UISearchBar) { view .removeGestureRecognizer(recognizer) } 

我更喜欢这一

 view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dismissKeyboardFromView:")) 

只要把它放在覆盖viewDidLoad函数的任何一个子类UIViewController你希望它发生,然后把下面的代码放在你的项目中一个新的空文件名为“UIViewController + dismissKeyboard.swift”:

 import UIKit extension UIViewController { // This function is called when the tap is recognized func dismissKeyboardFromView(sender: UITapGestureRecognizer?) { let view = sender?.view view?.endEditing(true) } } 

我有你的家庭

 override func viewDidLoad() { super.viewDidLoad() /*This ensures that our view loaded*/ self.textField.delegate = self /*we select our text field that we want*/ self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard"))) } func dismissKeyboard(){ /*this is a void function*/ textField.resignFirstResponder() /*This will dismiss our keyboard on tap*/ } 

如果你有其他的观点,应该接受触摸,你必须设置cancelsTouchesInView = false

喜欢这个:

 let elsewhereTap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) elsewhereTap.cancelsTouchesInView = false self.view.addGestureRecognizer(elsewhereTap) 

我发现这个简单的解决scheme:1.添加UITapGestureRecognizer到你的视图控制器2.添加IBAction到你的UITapGestureRecognizer 3.最后你可以辞去第一个响应者

 class ViewController: UIViewController { @IBOutlet var tap: UITapGestureRecognizer! @IBOutlet weak var label: UILabel! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func dismissUsingGesture(_ sender: UITapGestureRecognizer) { self.textField.resignFirstResponder() label.text = textField.text! } } 

对于Swift3

在viewDidLoad中注册一个事件识别器

 let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyBoard)) 

那么我们需要在相同的viewDidLoad中将该手势添加到视图中。

 self.view.addGestureRecognizer(tap) 

那么我们需要初始化注册的方法

 func hideKeyBoard(sender: UITapGestureRecognizer? = nil){ view.endEditing(true) } 

为了build立正确的答案,我总是使用以下扩展名:

 extension UIApplication { /// Dismiss keyboard from key window. open static func endEditing(_ force: Bool = false) { shared.keyWindow?.endEditing(force) } } 

这样,如果我试图取消编辑的类没有view属性或不是UIView的子类,我可以调用UIApplication.endEditing()

这是一个简洁的方法:

 let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:))) endEditingTapGesture.cancelsTouchesInView = false view.addGestureRecognizer(endEditingTapGesture) 
 override func viewDidLoad() { super.viewDidLoad() self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap))) } func tap(sender: UITapGestureRecognizer){ print("tapped") view.endEditing(true) } 

试试这个,这是工作