【问题标题】:preferredStatusBarStyle is not working [duplicate]preferredStatusBarStyle 不起作用[重复]
【发布时间】:2018-01-04 11:13:33
【问题描述】:

我曾经在我的项目中使用setStatusBarStyle,它工作正常,但它已被弃用,所以我使用preferredStatusBarStyle,它不起作用。 知道我已经:

  1. 调用方法setNeedsStatusBarAppearanceUpdate。
  2. 在 info.plist 中将“基于视图控制器的状态栏外观”设置为 NO
  3. 重写函数

    • (UIStatusBarStyle)preferredStatusBarStyle { 返回 UIStatusBarStyleLightContent; }

    这个函数没有被调用

注意:我正在使用导航控制器。

【问题讨论】:

标签: ios objective-c swift xcode statusbar


【解决方案1】:

这里是Apple Guidelines/Instruction关于状态栏更改。

如果您想设置状态栏样式,应用程序级别然后在您的.plist 文件中将UIViewControllerBasedStatusBarAppearance 设置为NO。并在您的 appdelegate > didFinishLaunchingWithOptions 添加以下代码(以编程方式,您可以从应用程序委托中完成)。

目标 C

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];

斯威夫特

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    application.statusBarStyle = .lightContent
    return true
}

如果您想设置状态栏样式,请在视图控制器级别执行以下步骤:

  1. 如果只需要在 UIViewController 级别设置状态栏样式,请在 .plist 文件中将 UIViewControllerBasedStatusBarAppearance 设置为 YES
  2. 在viewDidLoad添加函数-setNeedsStatusBarAppearanceUpdate

  3. 在您的视图控制器中覆盖 preferredStatusBarStyle。

目标 C

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNeedsStatusBarAppearanceUpdate];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

斯威夫特

override func viewDidLoad() {
    super.viewDidLoad()
    self.setNeedsStatusBarAppearanceUpdate()
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

根据状态栏样式设置级别设置.plist的值。


您可以在应用程序启动期间或视图控制器的 viewDidLoad 期间设置状态栏的背景颜色。

extension UIApplication {

    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }

}

// Set upon application launch, if you've application based status bar
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
        return true
    }
}


or 
// Set it from your view controller if you've view controller based statusbar
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
    }

}



结果如下:


【讨论】:

  • 这是唯一对我有用的东西,但它已被弃用。
  • viewcontroller 包裹在 UINavigationController 中是不行的
  • 如果你的应用使用navigationController,你也应该实现childViewControllerForStatusBarStyle。
  • 我在这里添加了我的答案,请看一下。 stackoverflow.com/a/56801660/299610
猜你喜欢
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 2017-07-19
  • 2015-07-04
  • 2012-10-26
相关资源
最近更新 更多