UISearchController 在调用时更改状态栏颜色

UISearchController changing status bar color on invocation

我的应用程序中有以下代码,特别是在设置我的 UISearchControllerviewDidLoad: 中。

self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = NO;
self.searchController.searchBar.scopeButtonTitles = @[];
self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;

[_tableView setTableHeaderView:_searchController.searchBar];

每当调用搜索栏(添加到 tableView)时,UIStatusBar 颜色从 UIStatusBarStyleLightContent 变为深色(白色变为黑色)。现在,我想出了如果我设置,

self.definesPresentationContext = NO;

以下内容:

self.definesPresentationContext = YES;

问题已解决,UIStatusBar 颜色得以保留。然而,另一个问题出现了。当 self.definesPresentationContext 设置为 YES ,在调用搜索栏时出于某种原因向下移动,巧合地(或理所当然地)就在 UIRefreshControl 底部显示在 tableView.

的下方

如果您希望视图控制器定义状态栏的外观,将 View-controller based status bar appearance 设置为 No 不是解决方案。

我的解决方案包括两件事:

  1. 确保呈现视图控制器已将 definesPresentationContext 设置为 YES
  2. 确保推送的视图控制器和推送视图控制器都位于导航栏下方(将extendedLayoutIncludesOpaqueBars设置为YES

我需要完全控制我的状态栏颜色。我使用扩展 found here 来确保可见视图控制器正在设置首选状态栏颜色。

因此,对我来说,有必要覆盖 UISearchController 并覆盖 preferredStatusBarStyle 和 return 我想要的样式。

搜索控制器出现(激活)时显示的状态栏属于搜索控制器。要设置首选状态栏样式,您必须向 UISearchController 添加一个类别,然后重写 preferredStatusBarStyle 方法。

以下是类别的实现文件示例:

@implementation UISearchController (Customization)

-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end

或者我们可以在 Swift 上写一个扩展(版本 2,但您可以轻松地将其转换为版本 3):

extension UISearchController {

   override public func preferredStatusBarStyle() -> UIStatusBarStyle{
      if Theme.lightTheme() {
          return UIStatusBarStyle.Default
      }
      else {
          return UIStatusBarStyle.LightContent
      }
   }
}

其中 Theme 是调节应用颜色主题的 class。

从 iOS 10(也许更早?)开始,如果您在 Info.plist 中将 "View controller-based status bar appearance" 设置为 YES,只需在包含 UISearchController 的 UIViewController 中设置 preferredStatusBarStyle英寸

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

(您不需要子类化或创建 UISearchController 的 category/extension 来覆盖 preferredStatusBarStyle...它使用您在 UIViewController 中设置的 preferredStatusBarStyle)

如果您 ViewController 在 TabBarController 中,那么 -

而不是 self.definesPresentationContext = YES;

使用 self.tabBarController.definesPresentationContext = YES;

在上述情况下这对我有用。