键盘完成键操作 swift iOS 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24775678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
keyboard done key action swift iOS doesn't work
提问by Giorgio Nocera
I'm new in stackoverflow, I have a problem with new swift code. I have custom the return button on keyboard with "Done", but when I tap on it, don't befall anything... How can I hide the keyboard on tap it? I have added a code (found on this site) for hide the keyboard when you tap somewhere ,not in the keyboard, but I can't custom it with tap on "done" button... Thank you before!!
我是 stackoverflow 的新手,我对新的 swift 代码有疑问。我用“完成”自定义了键盘上的返回按钮,但是当我点击它时,不要遇到任何事情......我如何在点击它时隐藏键盘?我添加了一个代码(在这个网站上找到),当你点击某个地方时隐藏键盘,而不是在键盘中,但我无法通过点击“完成”按钮来自定义它......谢谢你!
回答by Greg
You need to implement delegate method which is called when you hit done button:
您需要实现点击完成按钮时调用的委托方法:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
You also need to conform to UITextFieldDelegate protocol:
您还需要符合 UITextFieldDelegate 协议:
// I assume you override UIViewController class. If not add UITextFieldDelegate to your class
class MyViewController: UIViewController, UITextFieldDelegate
The last thing is set up your class to be a text field delegate:
最后一件事是将您的类设置为文本字段委托:
textField.delegate = self
回答by Stephane Paquet
textField.delegate = self
can be replaced by
可以替换为
This will create the necessary connections between your View, its component and will make the textFieldShouldReturn method work as expected.
这将在您的视图及其组件之间创建必要的连接,并使 textFieldShouldReturn 方法按预期工作。
回答by MatthiasFranz
The protocol methods have new signatures (Swift 4.1). IE:
协议方法有新的签名(Swift 4.1)。IE:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
As the protocol methods are optional, using a wrong signature will silently fail.
由于协议方法是可选的,使用错误的签名将无声地失败。