gpt4 book ai didi

ios - SwiftUI:为特定 View 设置状态栏颜色

转载 作者:行者123 更新时间:2023-12-01 18:03:55 25 4
gpt4 key购买 nike

我一直在尝试为我的应用程序的状态栏颜色设置一个 View 。

我已经尝试过这里列出的解决方案..' How to change Status Bar text color in iOS ' 但这为整个应用程序设置了它。

我想要的是状态栏颜色为在 SceneDelegate.swift 中设置的 rootViewController 设置白色文本,然后为所有其他 View 默认设置(根据暗模式从白色更改为黑色)。

有任何想法吗?

最佳答案

状态栏内容颜色可以根据每个 View Controller 进行修改,但 SwiftUI 最常见的情况是只使用一个 View Controller ,即根托管 View Controller 。所以它需要插入那个根 Controller 改变preferredStatusBarStyle属性,在基类中是只读的。
所以想法是覆盖默认 UIHostingController有可能改变 preferredStatusBarStyle重视和使用自定义Environment值,因此任何内部 SwiftUI subview 都可以修改该首选内容样式。
这是方法,scratch,(假设目标 Info.plist 配置正确)

class LocalStatusBarStyle { // style proxy to be stored in Environment
fileprivate var getter: () -> UIStatusBarStyle = { .default }
fileprivate var setter: (UIStatusBarStyle) -> Void = {_ in}

var currentStyle: UIStatusBarStyle {
get { self.getter() }
set { self.setter(newValue) }
}
}

// Custom Environment key, as it is set once, it can be accessed from anywhere
// of SwiftUI view hierarchy
struct LocalStatusBarStyleKey: EnvironmentKey {
static let defaultValue: LocalStatusBarStyle = LocalStatusBarStyle()
}

extension EnvironmentValues { // Environment key path variable
var localStatusBarStyle: LocalStatusBarStyle {
get {
return self[LocalStatusBarStyleKey.self]
}
}
}

// Custom hosting controller that update status bar style
class MyHostingController<Content>: UIHostingController<Content> where Content: View {
private var internalStyle = UIStatusBarStyle.default

@objc override dynamic open var preferredStatusBarStyle: UIStatusBarStyle {
get {
internalStyle
}
set {
internalStyle = newValue
self.setNeedsStatusBarAppearanceUpdate()
}
}

override init(rootView: Content) {
super.init(rootView:rootView)

LocalStatusBarStyleKey.defaultValue.getter = { self.preferredStatusBarStyle }
LocalStatusBarStyleKey.defaultValue.setter = { self.preferredStatusBarStyle = $0 }
}

@objc required dynamic init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
用法..
  • 场景委托(delegate)中的某处
  • func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // ...
    window.rootViewController = MyHostingController(rootView: contentView)
  • 内容 View 中的某处
  •    struct ContentView: View {
    @Environment(\.localStatusBarStyle) var statusBarStyle

    ...
    var body: some View {
    ZStack {
    ....
    NavigationView {
    NavigationLink(destination: ...) {
    ...
    }
    .onAppear {
    self.statusBarStyle.currentStyle = .lightContent
    }
    .onDisappear {
    self.statusBarStyle.currentStyle = .default
    }
    }
    }
    }
    }
    backup

    关于ios - SwiftUI:为特定 View 设置状态栏颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59569503/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com