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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24126678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:43:28  来源:igfitidea点击:

Close iOS Keyboard by touching anywhere using Swift

iosswiftuikeyboard

提问by lagoon

I have been looking all over for this but I can't seem to find it. I know how to dismiss the keyboard using Objective-Cbut I have no idea how to do that using Swift? Does anyone know?

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

回答by Esqarrouth

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

Here is another way to do this task if you are going to use this functionality in multiple UIViewControllers:

如果您要在多个中使用此功能,这是执行此任务的另一种方法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)
    }
}

Now in every UIViewController, all you have to do is call this function:

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

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

This function is included as a standard function in my repo which contains a lot of useful Swift Extensions like this one, check it out: https://github.com/goktugyil/EZSwiftExtensions

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

回答by King-Wizard

An answer to your question on how to dismiss the keyboard in Xcode 6.1 using Swift below:

关于如何使用 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).

此信息来源)。

回答by Fahim Parkar

Swift 4 working

斯威夫特 4 工作

Create extension as below & call hideKeyboardWhenTappedAround()in your Base view controller.

创建如下扩展并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)
    }
}

Most important thing to call in your Base View Controller so that no need to call all time in all view controllers.

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

回答by Dash

You can call

你可以打电话

resignFirstResponder()

on any instance of a UIResponder, such as a UITextField. If you call it on the view that is currently causing the keyboard to be displayed then the keyboard will dismiss.

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

回答by Naishta

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

}

回答by Yerbol

for Swift 3 it is very simple

对于 Swift 3,它非常简单

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

if you want to hide keyboard on pressing RETURN key

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

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

but in second case you will also need to pass delegate from all textFields to the ViewController in the Main.Storyboard

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

回答by NikaE

Swift 3: Easiest way to dismiss keyboard:

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
    }

回答by modocache

Dash's answer is correct and preferred. A more "scorched earth" approach is to call view.endEditing(true). This causes viewand all its subviews to resignFirstResponder. If you don't have a reference to the view you'd like to dismiss, this is a hacky but effective solution.

Dash 的回答是正确的,也是首选。更“焦土”的方法是调用view.endEditing(true). 这将导致view及其所有子视图变为resignFirstResponder. 如果您没有对要关闭的视图的引用,这是一个笨拙但有效的解决方案。

Note that personally I think you should have a reference to the view you'd like to have resign first responder. .endEditing(force: Bool)is a barbaric approach; please don't use it.

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

回答by William Hu

swift 5just two lines is enough. Add into your viewDidLoadshould work.

swift 5两行就够了。添加到您的viewDidLoad应该工作中。

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

If your tap gesture blocked some other touches, then add this line:

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

tapGesture.cancelsTouchesInView = false

回答by Hardik Bar

Use IQKeyboardmanagerthat will help you solve easy.....

使用IQKeyboardmanager可以帮助您轻松解决.....

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

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

![ how to disable the keyboard..][1]

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