使用Swift触摸任何地方关闭iOS键盘

lag*_*oon 376 uikeyboard ios swift

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

Esq*_*uth 1220

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.
@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}
Run Code Online (Sandbox Code Playgroud)

如果要在多个中使用此功能,这是执行此任务的另一种方法UIViewControllers:

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

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}
Run Code Online (Sandbox Code Playgroud)

这个函数作为标准函数包含在我的repo中,其中包含很多有用的Swift Extensions,请查看:https://github.com/goktugyil/EZSwiftExtensions

  • 刚发现这个问题并实现了这个方法.tableView/UICollectionView的"didSelectRow"没有调用字面意思的事情让我抓狂.解决方案是:只需将其添加到您的扩展名:`tap.cancelsTouchesInView = false`.这至少解决了我的问题.希望这有助于某人 (43认同)
  • 从第一个答案中的Swift 2开始,替换这一行 - >点击:UITapGestureRecognizer = UITapGestureRecognizer(target:self,action:#selector(MyViewController.dismissKeyboard)) (19认同)
  • 这是我遇到过的最有用的扩展之一!谢谢!我要扩展的唯一警告是这会干扰`didSelectRowAtIndexPath`. (11认同)
  • "看看我的回购"是新的"听到我的新混音带":P (9认同)
  • 这个答案有问题,我想在视图中有一个按钮,我想在其中执行此操作,当键盘打开并单击该按钮时,键盘将消失,但我无法获得完整的按钮操作,有些奇怪行为 (4认同)
  • 这非常有效,谢谢 (3认同)
  • 它打破了tableviewcell在tableviewcontroller上的segue (2认同)

Kin*_*ard 115

关于如何使用下面的Swift关闭Xcode 6.1键盘的问题的答案:

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

}
Run Code Online (Sandbox Code Playgroud)

(此信息的来源).

  • 很棒的代码,谢谢!touchesBegan正是我想要的:) (6认同)
  • 应该有更多的赞成,我需要的一切 (4认同)
  • 这对我来说不太合适.如果我点击视图控制器的视图就可以了.如果我点击视图中的控件项,键盘不会消失. (4认同)

Das*_*ash 36

你可以打电话

resignFirstResponder()
Run Code Online (Sandbox Code Playgroud)

在任何UIResponder实例上,例如UITextField.如果在当前导致键盘显示的视图上调用它,则键盘将关闭.

  • 在您不确切知道第一个响应者的情况下,resignFirstResponder()可能会导致一堆麻烦.Esq的答案如下(使用view.doneEditing())更合适 (5认同)
  • 它对我不起作用.下面的Esq答案就可以了. (3认同)

Fah*_*kar 32

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)
    }
}
Run Code Online (Sandbox Code Playgroud)


Nai*_*hta 20

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

}
Run Code Online (Sandbox Code Playgroud)


小智 18

对于Swift 3来说非常简单

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

如果你想按RETURN键隐藏键盘

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}
Run Code Online (Sandbox Code Playgroud)

但在第二种情况下,您还需要将委托从所有textField传递到Main.Storyboard中的ViewController


Nik*_*kaE 11

Swift 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
    }
Run Code Online (Sandbox Code Playgroud)


mod*_*che 10

Dash的答案是正确和首选的.一个更"焦土"的方法是打电话view.endEditing(true).这会导致view其所有子视图resignFirstResponder.如果你没有引用你想解雇的视图,这是一个hacky但有效的解决方案.

请注意,我个人认为您应该参考您希望辞职的第一响应者..endEditing(force: Bool)是一种野蛮的做法; 请不要使用它.


har*_*bar 9

![如何禁用键盘..] [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)
  }
}
Run Code Online (Sandbox Code Playgroud)


gog*_*elj 9

在故事板中:

  1. 选择TableView
  2. 从右侧选择属性检查器
  3. 在键盘部分 - 选择所需的关闭模式


Dav*_*eek 9

斯威夫特3:

使用Selectoras参数进行扩展,以便能够在dismiss函数中执行其他操作,并cancelsTouchesInView防止在视图的其他元素上触摸时出现失真.

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

用法:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}

func dismissKeyboard() {
    view.endEditing(true)
    // do aditional stuff
}
Run Code Online (Sandbox Code Playgroud)


小智 9

在 swift 你可以使用

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

}
Run Code Online (Sandbox Code Playgroud)


小智 8

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

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

    func dismissKeyboardView() {
        view.endEditing(true)
    }
}
Run Code Online (Sandbox Code Playgroud)

这行tap.cancelsTouchesInView = false很关键:它确保UITapGestureRecognizer不会阻止视图上的其他元素接收用户交互。

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

然后,如上所述,可以在各个View Controller中启用此行为:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}
Run Code Online (Sandbox Code Playgroud)


Jar*_*ger 8

将此扩展添加到您的 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)
  }
}
Run Code Online (Sandbox Code Playgroud)


JIE*_*ANG 7

如果您使用滚动视图,它可能会更简单.

只需选择Dismiss interactively故事板.


小智 7

在Swift 4中,添加@objc:

在viewDidLoad中:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)
Run Code Online (Sandbox Code Playgroud)

功能:

@objc func dismissKeyboard() {
  view.endEditing(true)
}
Run Code Online (Sandbox Code Playgroud)


Wil*_* Hu 6

迅速5仅仅两行就足够了。添加到您的viewDidLoad作品中。

 let tapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
 view.addGestureRecognizer(tapGesture)
Run Code Online (Sandbox Code Playgroud)

如果您的点击手势阻止了其他触摸,请添加以下行:

tapGesture.cancelsTouchesInView = false
Run Code Online (Sandbox Code Playgroud)


Art*_*tem 6

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

view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:))))
Run Code Online (Sandbox Code Playgroud)


小智 5

  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)
  }
}
Run Code Online (Sandbox Code Playgroud)


Noo*_*ath 5

为了扩展Esqarrouth的答案,我总是使用以下命令来关闭键盘,尤其是如果我要从中关闭键盘的类没有view属性和/或不是的子类时UIView

UIApplication.shared.keyWindow?.endEditing(true)
Run Code Online (Sandbox Code Playgroud)

并且,为方便起见,对该UIApplcation类进行了以下扩展:

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

}
Run Code Online (Sandbox Code Playgroud)


小智 5

作为一名新手程序员,当人们产生更多熟练和不必要的回答时,它可能会令人困惑......你不必做上面显示的任何复杂的事情!......

这是最简单的选项...如果键盘出现以响应文本字段 - 在触摸屏功能内部只需添加resignFirstResponder功能.如下图所示 - 键盘将关闭,因为第一响应者已释放(退出响应者链)...

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


Suk*_*ukh 5

我使用 IQKeyBoardManagerSwift 作为键盘。这个用起来很简单。只需添加 pod 'IQKeyboardManagerSwift'

导入 IQKeyboardManagerSwift 并didFinishLaunchingWithOptionsAppDelegate.

///add this line 
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.enable = true
Run Code Online (Sandbox Code Playgroud)