根据时间更改状态栏颜色

changing status bar color depending on time

不确定是否可行,但是有没有办法根据时间更改状态栏颜色?我在摆弄这段代码:

import UIKit

class testTimeController: UIViewController{

func lightstatusbar() {
var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
 }
}

  func darkstatusbar() {
var preferredStatusBarStyle: UIStatusBarStyle {
    return .default
}
}

override func viewDidLoad() {
    super.viewDidLoad()
let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)

 switch hour{
    case 1..<6: lightstatusbar()
        break
    case 7..<18: darkstatusbar()
        break
    case 19..<24: lightstatusbar()
        break
    default: darkstatusbar()
    }
}

是的,但只是实施和覆盖

override var preferredStatusBarStyle: UIStatusBarStyle {
    let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)

     switch hour{
    case 1..<6: .lightContent
        break
    case 7..<18: .darkContent
        break
    case 19..<24: .lightContent
        break
    default: .darkContent
}

不要将 var 放入另一个不会执行任何操作的方法中。

我使用了@SeanLintern88 方法,只是添加了 "return"

override var preferredStatusBarStyle: UIStatusBarStyle {
    let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)

    switch hour{
    case 1..<6: return.lightContent

    case 7..<18: return.default

    case 19..<24: return.lightContent

    default: return.default
    }
}

其他答案对我不起作用,所以这是我的工作解决方案,关于这个 answer:

步骤 1 将以下内容添加到您的 info.plist:

View controller-based status bar appearance 布尔值 NO

步骤 2 将此添加到 AppDelegate.swift 中的 application(_:didFinishLaunchingWithOptions:):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

  let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)

  switch hour {
  case 1..<6:
    UIApplication.shared.statusBarStyle = .lightContent
  case 7..<18:
    UIApplication.shared.statusBarStyle = .default
  case 19..<24:
    UIApplication.shared.statusBarStyle = .lightContent
  default:
    UIApplication.shared.statusBarStyle = .default
  }

  return true
}