在导航栏中显示搜索栏而不在 iOS 11 上滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46239883/
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
Show search bar in navigation bar without scrolling on iOS 11
提问by Jonathan
I'm attaching a UISearchController to the navigationItem.searchController
property of a UITableViewController on iOS 11. This works fine: I can use the nice iOS 11-style search bar.
我navigationItem.searchController
在 iOS 11 上将UISearchController 附加到UITableViewController的属性。这很好用:我可以使用漂亮的 iOS 11 风格的搜索栏。
However, I'd like to make the search bar visible on launch. By default, the user has to scroll up in the table view to see the search bar. Does anyone know how is this is possible?
但是,我想让搜索栏在启动时可见。默认情况下,用户必须在表格视图中向上滚动才能看到搜索栏。有谁知道这怎么可能?
Left: default situation after launch. Right: search bar made visible (by scrolling up). I'd like to have the search bar visible after launch, as in the right screenshot.
左:启动后的默认情况。右:搜索栏可见(通过向上滚动)。我想让搜索栏在启动后可见,如右图所示。
I already found that the search bar can be made visible by setting the property hidesSearchBarWhenScrolling
of my navigation item to false. However, this causes the search bar to always be visible — even when scrolling down —, which is not what I want.
我已经发现可以通过将hidesSearchBarWhenScrolling
导航项的属性设置为 false来使搜索栏可见。但是,这会导致搜索栏始终可见 - 即使向下滚动 - 这不是我想要的。
回答by Jordan Wood
The following makes the scroll bar visible at first, then allows it to hide when scrolling:
以下使滚动条首先可见,然后在滚动时隐藏它:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 11.0, *) {
navigationItem.hidesSearchBarWhenScrolling = false
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if #available(iOS 11.0, *) {
navigationItem.hidesSearchBarWhenScrolling = true
}
}
Using isActive
didn't do what I wanted, it makes the scroll bar active (showing cancel button, etc.), when all I want is for it to be visible.
使用isActive
没有做我想要的,它使滚动条处于活动状态(显示取消按钮等),而我想要的只是让它可见。
回答by txaidw
You can set the property isActive
to true
after adding the searchController to the navigationItem
.
您可以将属性设置isActive
到true
加入searchController到后navigationItem
。
Just like this:
像这样:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
searchController.isActive = true
}
回答by rohit
For me it worked after adding following lines in viewDidLoad()
method:
对我来说,在viewDidLoad()
方法中添加以下几行后它起作用了:
navigationController?.navigationBar.prefersLargeTitles = true
navigationController!.navigationBar.sizeToFit()