如何在Swift中按下回车键后隐藏键盘?

266

我使用UITextfied,当我点击文本输入框时键盘会出现,但是当我按下return键时,键盘不会消失。我使用了以下代码:

func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
    return true;
}

方法 resignFirstResponder 在函数中没有起作用。


10
你是否考虑接受 RSC 的答案?接受答案是使这个网站运作的方式,并被认为是一个好习惯。 - Juan Boero
7
如果有任何答案符合您的要求,请标记为答案,以便其他人也可以从中获得帮助。 - Syed Md. Kamruzzaman
20个回答

8
我建议从RSC初始化该类:
import Foundation
import UIKit

// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

@IBOutlet var myTextField : UITextField?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.myTextField.delegate = self;
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func textFieldShouldReturn(textField: UITextField!) -> Bool {
    self.view.endEditing(true);
    return false;
}

}


8
用户在文本键盘上点击“完成”按钮时,将生成一个 Did End On Exit 事件;此时,我们需要告诉文本字段放弃控制权,以便键盘消失。为了实现这一点,我们需要在控制器类中添加一个动作方法。 选择ViewController.swift并添加以下动作方法:
@IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()}

在项目导航器中选择Main.storyboard,然后打开连接检查器。从“Did End On Exit”旁边的圆圈拖动到故事板中的黄色视图控制器图标上,然后释放。一个小弹出菜单将出现,其中包含一个动作的名称,这是我们刚刚添加的动作。单击textFieldDoneEditing动作以选择它,就完成了。


5

Swift

使用来自UITextFieldDelegate的可选函数。

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.endEditing(false)
}

false 表示该字段可以要求辞职。true - 强制辞职。


5

Swift 3

将以下代码添加到您的 VC 中

//hide keyboard when user tapps on return key on the keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    self.view.endEditing(true);
    return false;
}

对我来说可以


5
override func viewDidLoad() {
    super.viewDidLoad()

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

那么你将使用这个函数。
func handleScreenTap(sender: UITapGestureRecognizer) {
    self.view.endEditing(true)
}

3

确保您的textField代理已设置为编写textfield相关代码的视图控制器。

self.textField.delegate = self

2

你可以将此放置在任何地方,但不要放在UIButton中。

 func TextFieldEndEditing(text fiend name: UITextField!) -> Bool
{
    return (false)
}

然后,您可以将此代码放在按钮中(例如):
self.view.endEditing(true)

这对我很有帮助。

2

在您使用的视图控制器中:

//suppose you are using the textfield label as this

@IBOutlet weak var emailLabel: UITextField!
@IBOutlet weak var passwordLabel: UITextField!

//then your viewdidload should have the code like this
override func viewDidLoad() {
        super.viewDidLoad()

        self.emailLabel.delegate = self
        self.passwordLabel.delegate = self

    }

//then you should implement the func named textFieldShouldReturn
 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

// -- then, further if you want to close the keyboard when pressed somewhere else on the screen you can implement the following method too:

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

我喜欢touchesBegan功能,在Swift 4中发挥作用,谢谢。 - A.J. Hernandez

0

你应该将UITextfied与视图控制器的委托连接起来,以调用此功能。


0

一键隐藏键盘并在打开键盘时移动视图:Swift 5

override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
    view.addGestureRecognizer(tap)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}


   override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
 @objc func taped(){
    
    self.view.endEditing(true)
    
}

@objc func KeyboardWillShow(sender: NSNotification){
    
    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y == 0{
        self.view.frame.origin.y -= keyboardSize.height
    }
    
    
}

@objc func KeyboardWillHide(sender : NSNotification){
    
    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y != 0{
        self.view.frame.origin.y += keyboardSize.height
    }
    
}


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接