在导航栏中显示搜索栏,不要在 iOS11上滚动

我将 UISearchController 附加到 iOS11上 UITableViewController 的 navigationItem.searchController属性。这个工作很好: 我可以使用漂亮的 iOS11风格的搜索栏。

但是,我想让搜索栏在启动时可见。默认情况下,用户必须在表视图中向上滚动才能看到搜索栏。有人知道这怎么可能吗?

enter image description here enter image description here

左: 启动后的默认情况。右: 搜索栏可见(通过向上滚动)。我希望在启动后搜索栏可见,如在正确的屏幕截图。

我已经发现,通过将导航项的属性 hidesSearchBarWhenScrolling设置为 false,搜索栏可以显示出来。但是,这会导致搜索栏始终可见ーー即使在向下滚动时也是如此ーー这不是我想要的。

30628 次浏览

You can set the property isActive to true after adding the searchController to the navigationItem.

Just like this:

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
searchController.isActive = true
}

The following makes the search 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 search bar active (showing cancel button, etc.), when all I want is for it to be visible.

For me it worked after adding following lines in viewDidLoad() method:

navigationController?.navigationBar.prefersLargeTitles = true
navigationController!.navigationBar.sizeToFit()

On iOS 13, @Jordan Wood's answer didn't work. Instead I did:

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.performWithoutAnimation {
searchController.isActive = true
searchController.isActive = false
}
}
For (iOS 13.0, *) and SwiftUI

navigationController?.navigationBar.sizeToFit()

Example:


struct SearchBarModifier: ViewModifier {
let searchBar: SearchBar
func body(content: Content) -> some View {
content
.overlay(
ViewControllerResolver { viewController in
viewController.navigationItem.searchController = self.searchBar.searchController
viewController.navigationController?.navigationBar.sizeToFit()


}
.frame(width: 0, height: 0)
)
}
}