我正在使用UITextfied,而点击textfied键盘出现,但当我按下返回键,键盘没有消失。我使用了以下代码:
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
方法resignfirstresponder没有进入函数。
我正在使用UITextfied,而点击textfied键盘出现,但当我按下返回键,键盘没有消失。我使用了以下代码:
func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
return true;
}
方法resignfirstresponder没有进入函数。
当前回答
为了获得自动键盘撤销,我将以下代码放在自定义文本字段类的一个方法中:
textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)
替换你的出口名称为textField。
其他回答
为了获得自动键盘撤销,我将以下代码放在自定义文本字段类的一个方法中:
textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)
替换你的出口名称为textField。
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.
我建议从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;
}
}
斯威夫特3
将下面的代码添加到你的VC中
//hide keyboard when user tapps on return key on the keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true);
return false;
}
对我有用
不需要委派
你可以从UITextField为“Primary action triggers”创建一个动作出口,并在传入的sender参数上辞职第一响应者:
@IBAction func done(_ sender: UITextField) {
sender.resignFirstResponder()
}
超级简单。
(感谢斯科特·史密斯60秒的视频,让我知道了这一点:https://youtu.be/v6GrnVQy7iA)