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


当前回答

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

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

其他回答

如果你的viewController在UINavigationController下面。

子类UINavigationController并添加

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

ViewController的preferredStatusBarStyle将被调用。

对于iOS 13.4, UINavigationController类别中的preferredStatusBarStyle方法将不会被调用,swizzling似乎是唯一的选择,不需要使用子类。

例子:

分类标题:

@interface UINavigationController (StatusBarStyle)
+ (void)setUseLightStatusBarStyle;
@end

实现:

#import "UINavigationController+StatusBarStyle.h"
#import <objc/runtime.h>

@implementation UINavigationController (StatusBarStyle)

void (^swizzle)(Class, SEL, SEL) = ^(Class c, SEL orig, SEL new){
    Method origMethod = class_getInstanceMethod(c, orig);
    Method newMethod = class_getInstanceMethod(c, new);
    if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    else
        method_exchangeImplementations(origMethod, newMethod);
};

+ (void)setUseLightStatusBarStyle {
    swizzle(self.class, @selector(preferredStatusBarStyle), @selector(_light_preferredStatusBarStyle));
}

- (UIStatusBarStyle)_light_preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}    
@end

在AppDelegate.h中的用法:

#import "UINavigationController+StatusBarStyle.h"

[UINavigationController setUseLightStatusBarStyle];

@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
}

对于任何仍然与此斗争的人来说,这个简单的扩展在swift中应该为您解决这个问题。

extension UINavigationController {
    override open var childForStatusBarStyle: UIViewController? {
        return self.topViewController
    }
}

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

presentedViewController.modalPresentationCapturesStatusBarAppearance = true

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