当视图加载时使 UISearchBar 成为第一响应者

发布于 2024-08-21 20:15:31 字数 425 浏览 9 评论 0原文

我有一个简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

皇甫轩 2024-08-28 20:15:32

将其移至 -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 the UISearchBar 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文