在导航栏中显示搜索栏而不在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:28:27  来源:igfitidea点击:

Show search bar in navigation bar without scrolling on iOS 11

iosuinavigationitemuisearchcontroller

提问by Jonathan

I'm attaching a UISearchController to the navigationItem.searchControllerproperty 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?

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

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

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 hidesSearchBarWhenScrollingof 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 isActivedidn'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 isActiveto trueafter adding the searchController to the navigationItem.

您可以将属性设置isActivetrue加入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()