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

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

方法resignfirstresponder没有进入函数。


当前回答

Add UITextFieldDelegate to the class declaration: class ViewController: UIViewController, UITextFieldDelegate Connect the textfield or write it programmatically @IBOutlet weak var userText: UITextField! set your view controller as the text fields delegate in view did load: override func viewDidLoad() { super.viewDidLoad() self.userText.delegate = self } Add the following function func textFieldShouldReturn(userText: UITextField!) -> Bool { userText.resignFirstResponder() return true; } with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.

其他回答

斯威夫特3

将下面的代码添加到你的VC中

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

对我有用

Add UITextFieldDelegate to the class declaration: class ViewController: UIViewController, UITextFieldDelegate Connect the textfield or write it programmatically @IBOutlet weak var userText: UITextField! set your view controller as the text fields delegate in view did load: override func viewDidLoad() { super.viewDidLoad() self.userText.delegate = self } Add the following function func textFieldShouldReturn(userText: UITextField!) -> Bool { userText.resignFirstResponder() return true; } with all this your keyboard will begin to dismiss by touching outside the textfield aswell as by pressing return key.

简单的Swift 3解决方案: 将这个函数添加到以文本字段为特征的视图控制器中:

@IBAction func textField(_ sender: AnyObject) {
    self.view.endEditing(true);
}

然后打开你的助理编辑器,确保你的主。Storyboard位于视图的一侧,所需的视图controller.swift文件位于另一侧。单击一个文本字段,然后从右边的实用工具面板“显示连接检查器”选项卡中选择。从“Did End on Exit”控件拖动到swift文件中的上述函数。重复该场景中的任何其他文本字段,并链接到相同的函数。

为了获得自动键盘撤销,我将以下代码放在自定义文本字段类的一个方法中:

textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)

替换你的出口名称为textField。

斯威夫特

使用UITextFieldDelegate的可选函数。

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

False表示可以要求该字段辞职。真力辞职。