问题描述
在Swift中, [someTextField] .resignFirstResponder()
和 self.view.endEditing(true)
完成相同的任务 - 将键盘从用户的视图中隐藏,并对使用它的任何文本字段进行去焦点。我理解前者是特定于某个特定领域,而后者包含整个视图,但除了想要定位特定文本字段外,何时优先/推荐另一个?
In Swift, both [someTextField].resignFirstResponder()
and self.view.endEditing(true)
accomplish the same task - hiding the keyboard from the user's view and de-focusing whatever text field was using it. I understand that the former is specific to a particular field, while the latter encompasses the entire view, but other than wanting to target a specific text field, when is one preferred/recommended over the other?
推荐答案
someTextField.resignFirstResponder()
resignFirstResponder()
可以在您确切知道哪个文本字段是第一个响应者并且您想要重新签署其第一个响应者状态时使用。这可以比替代方案稍微更有效,但是如果你正在做一些事情,比如创建一个自定义控件,那么这很有意义。也许您有一个文本字段,当按下下一步按钮时,您想要摆脱键盘并显示日期选择器。在这里,我肯定会使用 resignFirstResponder()
someTextField.resignFirstResponder()
resignFirstResponder()
is good to use any time you know exactly which text field is the first responder and you want to resign its first responder status. This can be slightly more efficient then the alternative, but if you're doing something such as creating a custom control, this can make plenty of sense. Perhaps you have a text field, and when the "Next" button is pressed, you want to get rid of the keyboard and present a date picker, for example. Here, I would definitely use resignFirstResponder()
我通常会保留这种情况,因为无论出于何种原因,无论目前发生什么,我都绝对需要清除键盘。也许,我有一个幻灯片菜单?在滑出之前,无论发生什么,键盘都应该消失,所以我会确保所有都会重新启动其第一响应者状态。重要的是要注意 endEditing()
将查看子视图的整个层次结构,并确保第一个响应者撤销其状态。如果您已经有第一个响应者的具体引用,那么调用 resignFirstResponder()
会降低效率,但如果没有,则比查找该视图并让其重新签名更容易。
I typically reserve this for scenarios when I just absolutely need to clear the keyboard no matter what is currently going on, for whatever reason. Perhaps, I've got a slide-over menu? Just before this slides out, no matter what is going on, the keyboard should go away, so I'll make sure everything resigns its first responder status. It's important to note that endEditing()
will look through the entire hierarchy of subviews and make sure whatever is the first responder resigns its status. This makes it less efficient then calling resignFirstResponder()
if you already have a concrete reference to the first responder, but if not, it's easier than finding that view and having it resign.
这篇关于resignFirstResponder与endEditing键盘解雇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!