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

时间:2014-06-09 18:38:10

标签: ios swift uikeyboard

我一直在寻找这个,但我似乎无法找到它。我知道如何使用Objective-C关闭键盘,但我不知道如何使用Swift执行此操作?有谁知道吗?

40 个答案:

答案 0 :(得分:1139)

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中使用此功能,以下是执行此任务的另一种方法:

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

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

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

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

答案 1 :(得分:109)

关于如何使用下面的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)
    }

}

Source of this information)。

答案 2 :(得分:34)

你可以打电话

resignFirstResponder()

在UIReponder的任何实例上,例如UITextField。如果您在当前导致键盘显示的视图上调用它,则键盘将会解除。

答案 3 :(得分:26)

Swift 4正在工作

创建以下扩展名&amp;在基本视图控制器中调用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)
    }
}

答案 4 :(得分:19)

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

}

答案 5 :(得分:17)

对于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
}

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

答案 6 :(得分:10)

Dash的回答是正确和首选的。一个更加焦虑的土地&#34;方法是致电view.endEditing(true)。这会导致view及其所有子视图转到resignFirstResponder。如果你没有引用你想解雇的观点,这是一个愚蠢但有效的解决方案。

  

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

答案 7 :(得分:10)

斯威夫特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
    }

答案 8 :(得分:9)

在故事板中:

  1. 选择TableView
  2. 从右侧选择属性检查器
  3. 键盘部分中的
  4. - 选择您想要的解雇模式

答案 9 :(得分:9)

斯威夫特3:

使用Selector作为参数进行扩展,以便能够在解散函数和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
}

答案 10 :(得分:8)

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

答案 11 :(得分:7)

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

只需在故事板中选择Dismiss interactively

答案 12 :(得分:6)

在Swift 4中,添加@objc:

在viewDidLoad中:

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

功能:

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

答案 13 :(得分:6)

我发现最好的解决方案包括@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() 
}

答案 14 :(得分: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)
  }
}

答案 15 :(得分:5)

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

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

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

答案 16 :(得分:4)

将此扩展添加到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)
  }
}

答案 17 :(得分:4)

在swift中你可以使用

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

}

答案 18 :(得分:4)

我总是使用以下内容:

UIApplication.shared.keyWindow?.endEditing(true)

甚至作为扩展名:

extension UIApplication {

    /// Dismiss keyboard from key window.
    /// Example Usage: `UIApplication.endEditing(true)`.
    ///
    /// - Parameters:
    ///     - force: specify `true` to force first responder to resign.
    open class func endEditing(_ force: Bool = false) {
        shared.keyWindow?.endEditing(force)
    }
}

这样,如果我尝试取消编辑的类没有view属性或者不是UIView的子类,我可以调用UIApplication.endEditing(true)。< / p>

答案 19 :(得分:4)

这一个班轮从UIView中的所有(任何)UITextField中取消键盘

self.view.endEditing(true)

答案 20 :(得分:4)

我已经将IQKeyBoardManagerSwift用于键盘。这个用起来很简单。 只需添加pod'IQKeyboardManagerSwift'

导入IQKeyboardManager在didFinishLaunchingWithOptions中的AppDelegate上快速编写代码并编写代码。

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

答案 21 :(得分:3)

适用于Swift3

在viewDidLoad

中注册事件识别器
let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyBoard))

然后我们需要在同一个viewDidLoad中将手势添加到视图中。

self.view.addGestureRecognizer(tap)

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

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

答案 22 :(得分:2)

另一种可能性是只需添加一个大按钮,其中没有任何内容位于您可能需要触摸的所有视图下方。 给它一个名为:

的动作
.flex {
    background: green;
    display: flex;
}

.flex .item:first-child {
    background: red;
}

.flex .item:last-child {
    background: yellow;
    margin-left:auto;
}

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

答案 23 :(得分:2)

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

像这样:

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

答案 24 :(得分:2)

Location: http://example.com/a.php

试试这个,它正在运作

答案 25 :(得分:1)

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

    }

答案 26 :(得分:1)

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

答案 27 :(得分:1)

快速5 只需两行就足够了。添加到您的viewDidLoad应该可以。

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

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

tapGesture.cancelsTouchesInView = false

答案 28 :(得分:1)

这是一种简洁的方法:

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

答案 29 :(得分:1)

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

要关注@modocache's recommendation以避免调用view.endEditing(),您可以跟踪成为第一响应者的文本字段,但这很麻烦且容易出错。

另一种方法是在viewcontroller 中的所有文本字段上调用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()
    }
}

现在您可以在手势识别器中(或适合您的任何地方)呼叫dismissKeyboard()。缺点是,添加或删除字段时必须保留UITextField的列表。

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

答案 30 :(得分:1)

我找到了这个简单的解决方案: 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!
}
}

答案 31 :(得分:1)

我找到你了

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

答案 32 :(得分:1)

我更喜欢单行

#!/bin/bash

count=0          
num_args="$#"     

for (( i = 0; i < "$num_args"; i++ )); do
    num=`find . -type f  -perm /u=x,g=x,o=x -name "$1" | wc -l`
    count=$(( count + num ))
    shift
done

echo "$count"

将它放在重写viewDidLoad函数中,无论你希望它发生在哪个子类UIViewController中,然后将以下代码放在项目中名为“UIViewController + dismissKeyboard.swift”的新空文件中:

$ ./script "*.html" "*.txt"       # can add any number of arguments here

答案 33 :(得分:0)

Swift 3

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

答案 34 :(得分:0)

一个Swift4 + RxSwift示例(也导入RxGesture)

view.rx.tapGesture()
        .when(GestureRecognizerState.recognized)
        .subscribe({ _ in
            self.view.endEditing(true)
        })
        .disposed(by: disposeBag)

答案 35 :(得分:0)

自从我对@ 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)
    }

}

答案 36 :(得分:0)

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

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

答案 37 :(得分:0)

能够通过在window的{​​{1}}属性中添加全局轻敲手势识别器来实现此目的。

这是一个非常流行的方法,对于某些人来说可能不是理想的解决方案,但它对我有用。请让我知道此解决方案是否有陷阱。

AppDelegate

答案 38 :(得分:0)

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

例如

exampleTextField.endEditing(true)

答案 39 :(得分:0)

以下是使用 Swift 5 在2行中点击其他任意位置来关闭键盘的方法。

(我讨厌添加另一个答案,但是由于这是Google的最佳结果,因此我将帮助像我这样的新秀。)

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

添加以下两行:

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