我正在使用UITextfied,而点击textfied键盘出现,但当我按下返回键,键盘没有消失。我使用了以下代码:

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

方法resignfirstresponder没有进入函数。


当前回答

我讨厌给每个UIViewController添加相同的函数。 通过扩展UIViewController来支持UITextFieldDelegate,你可以提供一个默认行为“返回按下”。

extension UIViewController: UITextFieldDelegate{
    public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true;
    }
}

当你创建新的UIViewController和UITextField时,你所要做的就是在你的UIViewController中写一行代码。

override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self
}

你甚至可以通过在Main.storyboard中钩子委托来省略这一行代码。(使用“ctrl”从UITextField拖动到UIViewController)

其他回答

下面是Swift 3.0版本对peacetype注释的更新:

textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)

我建议从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;
}

}

在你正在使用的视图控制器中:

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

你可以把它放在任何地方,但不能放在UIButton中

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

然后你可以把这段代码放在一个按钮中(也是一个例子):

self.view.endEditing(true)

这对我很有效

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