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


当前回答

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

presentedViewController.modalPresentationCapturesStatusBarAppearance = true

不要忘记在呈现的视图控制器中重写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];

NavigationController或TabBarController是需要提供样式的。以下是我的解决方法:https://stackoverflow.com/a/39072526/242769

在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 iOS 10解决方案:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
 }

大多数答案都不包括UINavigationController的childViewControllerForStatusBarStyle方法的良好实现。根据我的经验,你应该处理这样的情况,当透明的视图控制器在导航控制器。在这些情况下,你应该把控制传递给你的模态控制器(visibleViewController),但不要在它消失的时候。

override var childViewControllerForStatusBarStyle: UIViewController? {
  var childViewController = visibleViewController
  if let controller = childViewController, controller.isBeingDismissed {
    childViewController = topViewController
  }
  return childViewController?.childViewControllerForStatusBarStyle ?? childViewController
}