我一直在寻找这个,但似乎找不到。我知道如何使用来关闭键盘,Objective-C
但是我不知道如何使用Swift
?有人知道吗?
我一直在寻找这个,但似乎找不到。我知道如何使用来关闭键盘,Objective-C
但是我不知道如何使用Swift
?有人知道吗?
Answers:
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)
}
如果要多次使用此功能,这是另一种执行此任务的方法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()
}
此函数作为标准函数包含在我的仓库中,其中包含许多类似这样的有用的Swift扩展,请查看:https : //github.com/goktugyil/EZSwiftExtensions
didSelectRowAtIndexPath
。
tap.cancelsTouchesInView = false
。那至少对我来说解决了。希望这对某人有帮助
有关以下有关如何使用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)
}
}
(此信息的来源)。
如下创建扩展名并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 View Controller中调用最重要的事情,这样就不需要一直在所有View Controller中调用。
你可以打电话
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
}
但是在第二种情况下,您还需要将所有textField的委托传递给Main.Storyboard中的ViewController
unrecognized selector sent to instance
了这段代码。
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
}
斯威夫特3:
使用Selector
as参数扩展,以便能够在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
}
使用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)
}
}
我发现最好的解决方案包括@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()
被使用(我想这并不罕见),从而导致了编译器问题。
然后,如上所述,可以在各个View Controller中启用此行为:
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
}
为了扩展Esqarrouth的答案,我总是使用以下命令来关闭键盘,尤其是如果我要从中关闭键盘的类没有view
属性和/或不是的子类时UIView
。
UIApplication.shared.keyWindow?.endEditing(true)
并且,为方便起见,对该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)
}
}
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)
}
}
我已经将IQKeyBoardManagerSwift用于键盘。它很容易使用。只需添加pod'IQKeyboardManagerSwift'
导入IQKeyboardManagerSwift并在didFinishLaunchingWithOptions
中编写代码AppDelegate
。
///add this line
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.enable = true
对于Swift3
在viewDidLoad中注册事件识别器
let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyBoard))
那么我们需要将手势添加到同一viewDidLoad中的视图中。
self.view.addGestureRecognizer(tap)
然后我们需要初始化注册方法
func hideKeyBoard(sender: UITapGestureRecognizer? = nil){
view.endEditing(true)
}
自从我对@ 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)
}
}
您还可以添加轻击手势识别器以使键盘退出。: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")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))
}
func tap(sender: UITapGestureRecognizer){
print("tapped")
view.endEditing(true)
}
试试这个,它正在工作
要遵循@modocache的建议避免调用view.endEditing()
,可以跟踪成为第一响应者的文本字段,但这很麻烦且容易出错。
一种替代方法是resignFirstResponder()
在viewcontroller中调用所有文本字段。这是创建所有文本字段的集合的示例(在我的情况下,无论如何都需要验证代码):
@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()
不是第一响应者的控件有问题,或者有一种简单且有保证的非笨拙的方式来跟踪当前的第一响应者,我很乐意听到!