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


当前回答

如果你的viewController在UINavigationController下面。

子类UINavigationController并添加

override var preferredStatusBarStyle: UIStatusBarStyle {
    return topViewController?.preferredStatusBarStyle ?? .default
}

ViewController的preferredStatusBarStyle将被调用。

其他回答

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

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

所以我实际上添加了一个category到UINavigationController,但是使用了这些方法:

-(UIViewController *)childViewControllerForStatusBarStyle;
-(UIViewController *)childViewControllerForStatusBarHidden;

让它们返回当前可见的UIViewController。这让当前可见视图控制器设置它自己的首选样式/可见性。

下面是它的完整代码片段:

迅速:

extension UINavigationController {

    public override func childViewControllerForStatusBarHidden() -> UIViewController? {
        return self.topViewController
    }

    public override func childViewControllerForStatusBarStyle() -> UIViewController? {
        return self.topViewController
    }
}

在objective - c中:

@interface UINavigationController (StatusBarStyle)

@end

@implementation UINavigationController (StatusBarStyle)

-(UIViewController *)childViewControllerForStatusBarStyle {
    return self.topViewController;
}

-(UIViewController *)childViewControllerForStatusBarHidden {
    return self.topViewController;
}

@end

为了更好地衡量,这是它如何在UIViewController中实现的:

在斯威夫特

override public func preferredStatusBarStyle() -> UIStatusBarStyle {
    return .LightContent
}

override func prefersStatusBarHidden() -> Bool {
    return false
}

在objective - c中

-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent; // your own style
}

- (BOOL)prefersStatusBarHidden {
    return NO; // your own visibility code
}

最后,确保你的app plist没有将“基于视图控制器的状态栏外观”设置为NO。要么删除这一行,要么将其设置为YES(我相信这是iOS 7的默认设置?)

注意,当使用self.navigationController.navigationBar.barStyle = UIBarStyleBlack;解决方案

请确保进入你的plist并设置“基于视图控制器的状态栏外观”为YES。如果不是,它将不起作用。

如果你的viewController在UINavigationController下面。

子类UINavigationController并添加

override var preferredStatusBarStyle: UIStatusBarStyle {
    return topViewController?.preferredStatusBarStyle ?? .default
}

ViewController的preferredStatusBarStyle将被调用。

除了serenn的回答,如果你用modalPresentationStyle(例如.overCurrentContext)呈现一个视图控制器,你也应该在新呈现的视图控制器上调用这个:

presentedViewController.modalPresentationCapturesStatusBarAppearance = true

不要忘记在呈现的视图控制器中重写preferredStatusBarStyle。