当前我正在尝试将UISearchController嵌入到我的应用程序中。但是,如果UINavigationBar是非半透明的,那么作为UISearchController属性的UISearchBar就无法正确显示。通常在点击UISearchBar属性后,UINavigationBar会向上移动,为UISearchBar腾出空间。您可以在以下屏幕截图上看到结果:
https://www.dropbox.com/s/172k63zr2bhj84t/Normal_behaviour.png?dl=0
但是,如果UINavigationBar的"半透明"属性设置为"否",UISearchBar将无法正确显示,因为状态栏的背景仍然是透明的,如您在以下屏幕截图中所见:
https://www.dropbox.com/s/v5cnxoj9ms6976r/Wrong_behaviour.png?dl=0
为了证明这种奇怪的行为,我修改了苹果公司提供的样本项目:
https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Introduction/Intro.html
在这里你可以下载修改后的版本:
https://www.dropbox.com/s/7icfe6kap98g1e8/TableSearchwithUISearchControllerObj-CandSwift_MODIFIED.zip?dl=0
修改在文件"APLMainTableViewController.m"的第33行。
这显然是一个错误(rdar://20942583)。
我的解决方法是设置
self.edgesForExtendedLayout = UIRectEdgeAll;
self.extendedLayoutIncludesOpaqueBars = YES;
这样可以使导航栏保持不透明。不利的一面是,即使看不到内容,内容也会在栏下流动,从而产生一些开销。
我只需要:
func viewDidLoad() {
extendedLayoutIncludesOpaqueBars = true
}
一种解决方法是在搜索即将变为活动之前使状态栏半透明,并在搜索即将变成非活动时删除半透明。
您可以通过将视图控制器注册为UISearchController
的委托,并实现willPresentSearchController
和willDismissSearchController
方法来完成此操作。例如(在Swift
中):
将视图控制器声明为UISearchController
:的委托
class MyViewController: UITableViewController, UISearchControllerDelegate
不要忘记实际将其设置为委托,例如在viewDidLoad
中添加:
searchController.delegate = self
最后:
func willPresentSearchController(searchController: UISearchController) {
navigationController?.navigationBar.translucent = true
}
func willDismissSearchController(searchController: UISearchController) {
navigationController?.navigationBar.translucent = false
}
好吧,这个调试起来非常痛苦,但修复起来也没那么糟糕。这一切都要归功于苹果改变导航栏外观的方式。可以通过创建一个UINavigationBarAppearance
对象,用您想要的视觉属性(即背景颜色等)配置它,然后将它分配给UINavigationBar.appearance()
上的standardAppearance
和scrollEdgeAppearance
来修复它-如果需要,可以有两个不同的实例,它们具有不同的设置。
一个简单的实现可能看起来像这样:
let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
appearance.backgroundColor = barColor
appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: textColor]
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
(用您选择的颜色自然替换barColor和textColor!)
如果有人遇到非半透明隐藏之类的问题,搜索栏u可能会出现以下问题:
self.definestPresentationContext=真实
问候