Note: This does not work for controllers inside UINavigationController, please see Tyson's comment below :)
Swift 3 - This will work controllers inside UINavigationController. Add this code inside your controller.
// Preferred status bar style lightContent to use on dark background.// Swift 3override var preferredStatusBarStyle: UIStatusBarStyle {return .lightContent}
Swift 5和SwiftUI
为SwiftUI创建一个名为HostingController.swift的新Swift文件
import Foundationimport UIKitimport SwiftUI
class HostingController: UIHostingController<ContentView> {override var preferredStatusBarStyle: UIStatusBarStyle {return .lightContent}}
class MyNavigationController: UINavigationController {override var preferredStatusBarStyle: UIStatusBarStyle {.lightContent}}
或
extension UINavigationController {open override var preferredStatusBarStyle: UIStatusBarStyle {.lightContent}}
Override childForStatusBarStyle within UINavigationController
childForStatusBarStyle (doc) - Called when the system needs the view controller to use for determining status bar style
According to Apple's documentation,
"If your container view controller derives its status bar style from one of its child view controllers, [override this property] and return that child view controller. If you return nil or do not override this method, the status bar style for self is used. If the return value from this method changes, call the setNeedsStatusBarAppearanceUpdate() method."
In other words, if you don't implement solution 3 here, the system will fall back to solution 2 above.
Subclass or extend UINavigationController
class MyNavigationController: UINavigationController {override var childForStatusBarStyle: UIViewController? {topViewController}}
或
extension UINavigationController {open override var childForStatusBarStyle: UIViewController? {topViewController}}
You can return any view controller you'd like above. I recommend one of the following:
topViewController (of UINavigationController) (doc) - The view controller at the top of the navigation stack
visibleViewController (of UINavigationController) (doc) - The view controller associated with the currently visible view in the navigation interface (hint: this can include "a view controller that was presented modally on top of the navigation controller itself")
Note: If you decide to subclass UINavigationController, remember to apply that class to your nav controllers through the identity inspector in IB.
@mainstruct ProjectApp: App {var body: some Scene {WindowGroup {//wrap main view in RootViewRootView {//Put the view you want your app to present hereContentView()//add necessary environment objects here}}}}