导航栏中的 UISearchBar
如何在导航栏中显示 UISearchBar?
我不知道该怎么做。
非常感谢您的帮助。
How can I show a UISearchBar in the NavigationBar?
I can't figure out how to do this.
Your help is very much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将 searchBar 置于 navigationBar 的中心:
将 searchBar 置于 navigationBar 的左侧/右侧:
To put searchBar into the center of navigationBar:
To put searchBar to the left/right side of navigationBar:
从 iOS 7 开始,UISearchDisplayController 默认支持此功能。设置 UISearchDisplayController 的
displaysSearchBarInNavigationBar = YES
即可轻松实现此操作。根据文档:
As of iOS 7, the UISearchDisplayController supports this by default. Set the UISearchDisplayController's
displaysSearchBarInNavigationBar = YES
to get this working easily.Per the documentation:
正如一位评论者指出的那样,使用
searchDisplayController.displaysSearchBarInNavigationBar = true
最终会隐藏任何现有的左/右栏按钮项目。我发现使用 iOS7 在
searchDisplayController
上的新属性将searchBar
添加到navigationBar
的两种不同方法。1) 基于 Nib 的方法
如果您使用 .xib,则可以为此值设置用户定义的运行时属性,并且无论出于何种原因,leftBarButtonItem 都会保持不变。我还没有使用 rightBarButtonItem 对其进行测试。
2) 代码(时机很重要)
如果您想用代码实现,时机似乎很重要。看来您必须首先将
searchBar
添加到navigationBar
,然后设置您的barButtonItem
。As one commenter noted, using
searchDisplayController.displaysSearchBarInNavigationBar = true
ends up hiding any existing left/right bar button items.I've found two different ways of adding a
searchBar
to anavigationBar
using iOS7's new property onsearchDisplayController
.1) Nib Based Approach
If you're using a .xib, you can set a User Defined Runtime Attribute for this value and for whatever reason, the leftBarButtonItem stays in tact. I have not tested it with a rightBarButtonItem.
2) Code (Timing Matters)
If you want to implement in code, timing seems to matter. It seems that you must add the
searchBar
to thenavigationBar
first, then set yourbarButtonItem
.查看 Apple 的 UICatalog 示例代码。它展示了如何以三种不同的方式使用新的
UISearchController
:模态方式、导航栏中以及导航栏下方。Check out Apple's UICatalog sample code. It shows how to use the new
UISearchController
in three different ways: modally, in nav bar, and below the navigation bar.导航栏中 UISearchBar 的目标 C 代码片段
阅读更多内容 这里
Objective C code snippet for UISearchBar in NavigationBar
Read more here