实现这一点的方法是创建一个具有适当位置和尺寸的 UIView,然后直接将其添加到 UIWindow:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var statusBarColorView: UIView?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window?.makeKeyAndVisible()
let v = UIView(frame: CGRect(x: 0, y: 0, width: window?.frame.size.width ?? 1024, height: 20))
v.backgroundColor = UIColor.white
v.translatesAutoresizingMaskIntoConstraints = false
window?.addSubview(v)
window?.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[v(==20)]",
options: [],
metrics: nil,
views: ["v": v]))
window?.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[v]-0-|",
options: [],
metrics: nil,
views: ["v": v]))
return true
}
这种方法的问题是您需要自己根据设备方向/当前显示的视图控制器隐藏/显示它。
更改颜色将如下所示:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.statusBarColorView?.backgroundColor = UIColor.blue
}
}
您肯定想根据您的颜色自定义 UIStatusBarStyle,您可以通过在 Info.plist 中为键 UIViewControllerBasedStatusBarAppearance 选择 YES 来实现此目的