我正在使用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没有进入函数。
当前回答
不需要委派
你可以从UITextField为“Primary action triggers”创建一个动作出口,并在传入的sender参数上辞职第一响应者:
@IBAction func done(_ sender: UITextField) {
sender.resignFirstResponder()
}
超级简单。
(感谢斯科特·史密斯60秒的视频,让我知道了这一点:https://youtu.be/v6GrnVQy7iA)
其他回答
你可以把它放在任何地方,但不能放在UIButton中
func TextFieldEndEditing(text fiend name: UITextField!) -> Bool
{
return (false)
}
然后你可以把这段代码放在一个按钮中(也是一个例子):
self.view.endEditing(true)
这对我很有效
在你正在使用的视图控制器中:
//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);
}
另一种主要使用故事板并轻松允许你拥有多个文本字段的方法是:
@IBAction func resignKeyboard(sender: AnyObject) {
sender.resignFirstResponder()
}
将视图控制器的所有文本字段连接到每个字段的Did End on Exit事件上的那个动作。
简单的Swift 3解决方案: 将这个函数添加到以文本字段为特征的视图控制器中:
@IBAction func textField(_ sender: AnyObject) {
self.view.endEditing(true);
}
然后打开你的助理编辑器,确保你的主。Storyboard位于视图的一侧,所需的视图controller.swift文件位于另一侧。单击一个文本字段,然后从右边的实用工具面板“显示连接检查器”选项卡中选择。从“Did End on Exit”控件拖动到swift文件中的上述函数。重复该场景中的任何其他文本字段,并链接到相同的函数。
下面是Swift 3.0版本对peacetype注释的更新:
textField.addTarget(nil, action:Selector(("firstResponderAction:")), for:.editingDidEndOnExit)