我遵循这个线程重写-preferredStatusBarStyle,但它没有被调用。 有什么选项我可以改变来启用它吗?(我在我的项目中使用xib。)


当前回答

在Swift中,对于任何类型的UIViewController:

在你的AppDelegate集合中:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    window!.rootViewController = myRootController
    return true
}

myRootController可以是任何类型的UIViewController,例如UITabBarController或UINavigationController。

然后,像这样重写这个根控制器:

class RootController: UIViewController {
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
}

这将改变状态栏在整个应用程序中的外观,因为根控制器只负责状态栏的外观。

记住在你的信息中将基于视图控制器的状态栏外观属性设置为YES。Plist使其工作(这是默认值)。

其他回答

如果有人正在使用一个导航控制器,并希望他们所有的导航控制器都有黑色风格,你可以在Swift 3中写一个扩展到UINavigationController,它将应用于所有的导航控制器(而不是一次分配给一个控制器)。

extension UINavigationController {

    override open func viewDidLoad() {
        super.viewDidLoad()

        self.navigationBar.barStyle = UIBarStyle.black
    }

}

@serenn上面的回答对于UINavigationControllers来说仍然是一个很好的例子。然而,对于swift 3, childViewController函数已经被更改为vars。所以UINavigationController扩展代码应该是:

override open var childViewControllerForStatusBarStyle: UIViewController? {
  return topViewController
}

override open var childViewControllerForStatusBarHidden: UIViewController? {
  return topViewController
}

然后在视图控制器中,它应该指示状态栏的样式:

override var preferredStatusBarStyle: UIStatusBarStyle {
   return .lightContent
}

在我的例子中,我意外地将视图/导航控制器呈现为UIModalPresentationStyle。overFullScreen,这导致preferredStatusBarStyle没有被调用。切换回UIModalPresentationStyle后。全屏,一切正常。

Hippo的回答:如果你正在使用UINavigationController,那么最好添加一个类别:

//  UINavigationController+StatusBarStyle.h:

@interface UINavigationController (StatusBarStyle)

@end



//  UINavigationController+StatusBarStyle.m:

@implementation UINavigationController (StatusBarStyle)

- (UIStatusBarStyle)preferredStatusBarStyle
{
    //also you may add any fancy condition-based code here
    return UIStatusBarStyleLightContent;
}

@end

这种解决方案可能比切换到即将被弃用的行为要好。

可能的根本原因

我也遇到了同样的问题,我发现这是因为我没有在我的应用程序窗口中设置根视图控制器。

我在UIViewController中实现了preferredStatusBarStyle,在UITabBarController中使用,它控制了屏幕上视图的外观。

当我设置根视图控制器指向这个UITabBarController时,状态栏的变化开始正确工作,正如预期的那样(preferredStatusBarStyle方法正在被调用)。

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    ... // other view controller loading/setup code

    self.window.rootViewController = rootTabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

替代方法(在iOS 9中已弃用)

另外,你也可以在每个视图控制器中调用以下方法之一,这取决于它的背景颜色,而不是必须使用setNeedsStatusBarAppearanceUpdate:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

or

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];

注意,如果你使用这个方法,你还需要在plist文件中将UIViewControllerBasedStatusBarAppearance设置为NO。