简体   繁体   English

按下按钮时以编程方式快速关闭键盘?

[英]Dismissing the keyboard when a button is pressed, programmatically with swift?

如何快速以编程方式按下按钮时关闭键盘?

There is also the so called "big hammer". 也有所谓的“大铁锤”。

Just call self.view.endEditing(true) 只需调用self.view.endEditing(true)

The documentation states the following for this method: 文档针对此方法声明以下内容:

Causes the view (or one of its embedded text fields) to resign the first responder status. 使视图(或其嵌入式文本字段之一)退出第一响应者状态。

It all depends on what triggered the keyboard to appear in the first place. 这完全取决于触发键盘首先出现的原因。 If you have a UITextField on your page that brought it up, you can call textField.resignFirstResponder() to hide the keyboard again. 如果页面上有一个UITextField可以将其调出,则可以调用textField.resignFirstResponder()再次隐藏键盘。

If you used some other object to bring up the keyboard, simply take the reference of whatever you used and call resignFirstResponder() on that object. 如果您使用其他对象来调动键盘,则只需引用您使用的对象,然后对该对象调用resignFirstResponder()

Example: 例:

Lets say you are using a button button1 to close the keyboard, and you have a textField1 that is triggering the keyboard. 假设您正在使用按钮button1关闭键盘,并且有一个textField1会触发键盘。

button1.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "buttonTapped"))

Then in your buttonTappedFunction 然后在你的buttonTappedFunction

func buttonTapped(){
  textField1.resignFirstResponder()
}

您必须在当前活动的UI元素(最有可能是UITextField )上调用resignFirstResponder

Setting the UITextfield delegate programmatically swift 2.2 Add UITextFieldDelegate in your class. 以编程方式快速设置UITextfield委托2.2在您的类中添加UITextFieldDelegate。

https://stackoverflow.com/a/31689406/5576747 https://stackoverflow.com/a/31689406/5576747

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM