我一直在到处找这个,但我似乎找不到。我知道如何解雇使用Objective-C键盘,但我不知道如何使用Swift?有人知道吗?


你可以打电话

resignFirstResponder()

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


Dash的回答是正确的。一个更“焦土”的方法是调用view. enditing (true)。这将导致视图及其所有子视图resignFirstResponder。如果您没有想要删除的视图的引用,这是一种俗气但有效的解决方案。

请注意,我个人认为你应该有一个引用的视图,你想要有辞职第一响应者. enditing (force: Bool)是一个野蛮的方法;请不要使用它。


下面是关于如何在Xcode 6.1中使用Swift消除键盘的回答:

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

}

(此信息的来源)。


override func viewDidLoad() {
    super.viewDidLoad()
          
    //Looks for single or multiple taps. 
     let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.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.
@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

如果你打算在多个uiviewcontroller中使用这个功能,这里有另一种方法来完成这个任务:

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

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

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

这个函数是我的repo中包含的标准函数,它包含了很多有用的Swift扩展,比如这个,看看:https://github.com/goktugyil/EZSwiftExtensions


您还可以添加一个点击手势识别器来重新使用键盘。: 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")
}

使用IQKeyboardmanager,将帮助您解决简单.....

/////////////////////////////////////////

[如何禁用键盘..][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)
  }
}

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

为了遵循@modocache的建议避免调用view. enditing(),您可以跟踪成为第一响应器的文本字段,但这很混乱且容易出错。

另一种方法是在视图控制器中的所有文本字段上调用resignFirstResponder()。下面是一个创建所有文本字段集合的示例(在我的情况下,验证代码无论如何都需要):

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

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

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


另一种可能是在你可能需要触摸的所有视图下面添加一个没有内容的大按钮。 给它一个名为:

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

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


在故事板:

选择TableView 在右边,选择属性检查器 在键盘部分-选择你想要的解散模式


我在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)

    }

//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
    }

}

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

我更喜欢这样一句话:

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

只要把它放在override 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*/
}

这一行代码辞去了UIView中所有UITextField的键盘

self.view.endEditing(true)

我发现最好的解决方案包括来自@Esqarrouth的接受答案,并进行了一些调整:

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

    func dismissKeyboardView() {
        view.endEditing(true)
    }
}

电话响了。cancelsTouchesInView = false是关键的:它确保UITapGestureRecognizer不会阻止视图上的其他元素接收用户交互。

方法解雇键盘()被更改为稍微不那么优雅的解雇keyboardview()。这是因为在我的项目相当旧的代码库中,有很多次已经使用了dismissKeyboard()(我想这并不少见),导致编译器问题。

然后,如上所述,这个行为可以在各个视图控制器中启用:

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

为了扩展Esqarrouth的答案,我总是使用以下方法来解除键盘,特别是如果我正在解除键盘的类没有view属性和/或不是UIView的子类。

UIApplication.shared.keyWindow?.endEditing(true)

并且,为了方便起见,下面是uiapplication类的扩展:

extension UIApplication {

    /// Dismisses the keyboard from the key window of the
    /// shared application instance.
    ///
    /// - Parameters:
    ///     - force: specify `true` to force first responder to resign.
    open class func endEditing(_ force: Bool = false) {
        shared.endEditing(force)
    }

    /// Dismisses the keyboard from the key window of this 
    /// application instance.
    ///
    /// - Parameters:
    ///     - force: specify `true` to force first responder to resign.
    open func endEditing(_ force: Bool = false) {
        keyWindow?.endEditing(force)
    }

}

如果你有其他视图也应该接收触摸,你必须设置 cancelsTouchesInView = false

是这样的:

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

斯威夫特3:

扩展选择器作为参数,能够做额外的东西在解散函数和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
}

我找到了一个简单的解决办法: 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!
}
}

斯威夫特3: 关闭键盘的最简单方法:

  //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
    }

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

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

如果你想隐藏键盘按回车键

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

但在第二种情况下,你还需要通过委托从所有文本字段的ViewController在主。故事板


作为一个新手程序员,当人们给出更熟练和不必要的回答时,可能会感到困惑……你不需要做上面所示的任何复杂的事情!

这是最简单的选择……在这种情况下,你的键盘出现在响应文本字段-在你的触摸屏函数中,只需添加resignFirstResponder函数。如下所示-键盘将关闭,因为First Responder被释放(退出Responder链)…

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

如果你使用滚动视图,它会简单得多。

只需在故事板中交互式地选择解散。


这里有一个简单的方法:

let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
endEditingTapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(endEditingTapGesture)

对于Swift3

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

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

然后我们需要在相同的viewDidLoad中添加手势到视图中。

self.view.addGestureRecognizer(tap)

然后我们需要初始化注册的方法

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

斯威夫特3

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

override func viewDidLoad() {
        super.viewDidLoad()

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))

}

func tap(sender: UITapGestureRecognizer){
        print("tapped")
        view.endEditing(true)
}

试试这个,很管用


在Swift 4中,添加@objc:

在viewDidLoad中:

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

功能:

@objc func dismissKeyboard() {
  view.endEditing(true)
}

你可以使用swift

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

}

Swift 4工作

创建扩展如下所示,并在你的基本视图控制器中调用hideKeyboardWhenTappedAround()。

//
//  UIViewController+Extension.swift
//  Project Name
//
//  Created by ABC on 2/3/18.
//  Copyright © 2018 ABC. All rights reserved.
//

import UIKit

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tapGesture = UITapGestureRecognizer(target: self, 
                         action: #selector(hideKeyboard))
        view.addGestureRecognizer(tapGesture)
    }

    @objc func hideKeyboard() {
        view.endEditing(true)
    }
}

最重要的是调用Base视图控制器这样就不需要在所有视图控制器中调用所有时间。


添加这个扩展到你的ViewController:

  extension UIViewController {
// Ends editing view when touches to view 
  open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    self.view.endEditing(true)
  }
}

我已经使用IQKeyBoardManagerSwift键盘。它很容易使用。 只需添加pod 'IQKeyboardManagerSwift'

导入IQKeyboardManagerSwift并在AppDelegate中的didFinishLaunchingWithOptions上编写代码。

///add this line 
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.enable = true

Swift 5只要两行就够了。添加到你的viewDidLoad应该工作。

 let tapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
 view.addGestureRecognizer(tapGesture)

如果你的点击手势阻止了一些其他的触摸,那么添加这一行:

tapGesture.cancelsTouchesInView = false

因为我编辑的@King-Wizard的回答被拒绝了,所以发布了一个新的答案。

让你的类成为UITextField的委托并重写touchesBegan。

斯威夫特4

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    //Called when 'return' key is pressed. Return false to keep the keyboard visible.
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        return true
    }

    // Called when the user clicks on the view (outside of UITextField).
    override func touchesBegan(touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

}

viewDidLoad()方法中只有一行代码:

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

可以通过在AppDelegate的窗口属性中添加全局点击手势识别器来实现这一点。

这是一种非常全面的方法,对某些人来说可能不是理想的解决方案,但对我来说很有效。请让我知道这个解决方案是否有任何陷阱。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Globally dismiss the keyboard when the "background" is tapped.
        window?.addGestureRecognizer(
            UITapGestureRecognizer(
              target: window, 
              action: #selector(UIWindow.endEditing(_:))
            )
        )

        return true
    }
}

一个简单的方法是选择文本字段并使用方法enditing (true)

e.g

exampleTextField.endEditing(true)

以下是如何通过点击其他地方来消除键盘,使用Swift 5只需两行。

(我讨厌添加另一个答案,但由于这是谷歌上的顶级结果,我将帮助像我这样的新手。)

在你的ViewController.swift中,找到viewDidLoad()函数。

加上这两行:

let tap: UIGestureRecognizer = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
        
view.addGestureRecognizer(tap)

如果你想解散键盘,当你想去下一个按钮动作或任何地方。

你可以简单地添加下面的行,替换你的文本字段名称。

billTextField.endEditing(真正的) 或 billTextField.resignFirstResponder ()


我没有看到它被提到过,但是NotificationCenter可以告诉你键盘何时打开和关闭。例如,如果你想改变cancelsTouchesInView或一起删除手势识别器,这可以被使用。

例子:

var dismissKeyboardGestureRecognizer = UITapGestureRecognizer()

override func viewDidLoad() {
    super.viewDidLoad()

    //Setup dismiss keyboard gesture
    self.dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))

    //Add Notifications
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name:UIResponder.keyboardDidShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name:UIResponder.keyboardDidHideNotification, object: nil)
}

@objc func keyboardDidShow() {
    dismissKeyboardGestureRecognizer.cancelsTouchesInView = true
    view.addGestureRecognizer(dismissKeyboardGestureRecognizer)
}

@objc func keyboardDidHide() {
    dismissKeyboardGestureRecognizer.cancelsTouchesInView = false
    view.removeGestureRecognizer(dismissKeyboardGestureRecognizer)
}

@objc func dismissKeyboard() {
    view.endEditing(true)
}

如何解散键盘时,你点击任何地方关闭它

 //Setup dismiss keyboard gesture
 let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

     view.addGestureRecognizer(tap)
 }
 //Calling this function when the tapped
 @objc func dismissKeyboard() {

    view.endEditing(true)
 }