SwiftUI设置状态栏样式 [英] SwiftUI setting status bar style
问题描述
我一直试图在我的SwiftUI应用中将状态栏设置为浅色文本,因为它具有深色背景.
I have been attempting to set the statusbar in my SwiftUI app to light text as it has a dark background.
我在多个站点上找到了该解决方案,但无法使其正常工作.
I found this solution on several sites but cannot get it to work.
HostingController.swift
HostingController.swift
import Foundation
import UIKit
import SwiftUI
class HostingController : UIHostingController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
这将在类声明行Reference to generic type 'UIHostingController' requires arguments in <...>
上返回错误,并建议使用Insert '<<#Content: View#>>'
修复.应用上述修复程序会导致错误Use of undeclared type '<#Content: View#>'
This returns an error on the class declaration line Reference to generic type 'UIHostingController' requires arguments in <...>
with a suggested fix of Insert '<<#Content: View#>>'
. Applying said fix results in the error Use of undeclared type '<#Content: View#>'
然后您将在SceneDelegate.swift
文件中更改window.rootViewController
.
You are then meant to change the window.rootViewController
in the SceneDelegate.swift
file.
SceneDelegate.swift
SceneDelegate.swift
...
// Create the SwiftUI view that provides the window contents.
let contentView = Login()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = HostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
...
这会在window.rootViewController
行Argument passed to call that takes no arguments
有人有什么想法吗?似乎很麻烦,只是设置状态栏颜色,我想这是一个相当普遍的要求.
Anyone got any ideas? Seems like a lot of bother just to set the status bar colour which I imagine would be a fairly common requirement.
推荐答案
您的HostingController需要具体类型的rootView:
Your HostingController needs a concrete type of the rootView:
class HostingViewController: UIHostingController<AnyView> {
@objc override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
然后在func scene(_ scene: UIScene, willConnectTo...
中将其用作rootViewController:
Then use it in func scene(_ scene: UIScene, willConnectTo...
as the rootViewController:
let contentView = ContentView()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = HostingViewController(rootView: AnyView(contentView.environmentObject(SessionStore())))
self.window = window
window.makeKeyAndVisible()
}
不幸的是,您不会在画布上看到任何差异,但是可以在模拟器上进行尝试.
You won't see any difference in canvas unfortunately, but try it on a simulator.
这篇关于SwiftUI设置状态栏样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!