当视图加载时使 UISearchBar 成为第一响应者
我有一个简单的 UIViewController
和一个 UISearchBar
,当视图加载时,我希望搜索栏立即成为第一个响应者,以便键盘显示并且它们可以启动立即输入他们的查询。我尝试在 viewWillAppear
中执行此操作,如下所示,但没有任何运气:
- (void)viewWillAppear:(BOOL)animated
{
[productSearchBar becomeFirstResponder];
[super viewWillAppear:animated];
}
是否还有其他地方我应该在 UISearchBar
上调用 becomeFirstResponder
或者我应该完全调用其他东西吗?
I have a simple UIViewController
and a UISearchBar
, when the view loads I want to have the search bar become the first responder right away so that the keyboard is showing and they can start typing their query right away. I tried doing it in viewWillAppear
like below without any luck:
- (void)viewWillAppear:(BOOL)animated
{
[productSearchBar becomeFirstResponder];
[super viewWillAppear:animated];
}
Is there another place that I should be calling becomeFirstResponder
on the UISearchBar
or should I be calling something else entirely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将其移至
-viewDidAppear
应该没问题。-becomeFirstResponder
拉起键盘(正如您所注意到的),并且您不应该在屏幕上之前执行动画。你可能会得到奇怪的互动。如果它根本不执行任何操作,那么几乎可以肯定
productSearchBar
是一个 IBOutlet,而您忘记了将其实际绑定到 Interface Builder 中的UISearchBar
。这是 UI 中“没有发生任何事情”的第一大原因。请注意,您不应该以这种方式访问您的 ivars;您应该将其设为属性并仅引用
self.productSearchBar
。苹果终于在他们的内存管理中发布了对此的正确解释Nib 对象的数量。切勿在访问器或-dealloc
之外访问您的 ivars。此规则将为您节省大量调试时间。Move this to
-viewDidAppear
and it should be fine.-becomeFirstResponder
pulls up the keyboard (as you note), and you shouldn't do animations before you're onscreen. You can get weird interactions.If it's not doing anything at all, then almost certainly
productSearchBar
is an IBOutlet and you've forgotten to actually tie it to theUISearchBar
in Interface Builder. This is the #1 reason for "nothing happens" in UI.Note that you shouldn't be accessing your ivars this way; you should make it a property and refer only to
self.productSearchBar
. Apple has finally posted a correct explanation of this in their Memory Management of Nib Objects. Never access your ivars outside of an accessor or-dealloc
. This rule will save you many hours of debugging.