SwiftUI自定义NavigationController时如何修改状态栏背景色?
我在SwiftUI App生命周期中尝试使用原生UINavigationController,于是创建了名为JDNavigationController的自定义导航控制器,仅添加了@Observable宏。
自定义的UIViewControllerRepresentable实现如下:
public struct NavigationControllerStack<Content: View>: UIViewControllerRepresentable { private let initialView: () -> Content @State private var controller = JDNavigationController() public init(content: @escaping () -> Content) { self.initialView = content } public func makeUIViewController(context: Context) -> JDNavigationController { let viewController = self.initialView() .environment(self.controller) .viewController self.controller.viewControllers = [ viewController ] return controller } public func updateUIViewController(_ uiViewController: JDNavigationController, context: Context) { } public typealias UIViewControllerType = JDNavigationController }
导航控制器功能正常,但我始终无法修改状态栏的背景色,当前状态栏显示为白色区域:

预览代码如下:
#Preview { NavigationControllerStack { ZStack { Color.purple .ignoresSafeArea(.all) VStack { Text("somethign") } } } }
我已经尝试了以下方法,但均无效:
- 使用外观函数
- 创建自定义视图控制器,添加Hosting Controller作为子视图并设置
hostingController.view.insetsLayoutMarginsFromSafeArea = false - 使用SwiftUI View的toolbar修饰符
通过视图调试器排查后,发现白色区域来自UIHostingController,但不确定具体解决办法。
补充说明:我编写了SwiftUI View的扩展,用于将SwiftUI视图转换为UIViewController:
extension View { public var viewController: UIViewController { UIHostingController(rootView: self) } }
JDNavigationController的完整实现:
@Observable public final class JDNavigationController: UINavigationController { public func pushView<V: View>( _ view: @autoclosure () -> V, animated: Bool = true ) { self.pushViewController( view() .environment(self) .viewController, animated: animated ) } public func presentView<V: View>( _ view: @autoclosure () -> V, animated: Bool = true, completion: (() -> Void)? = nil ) { self.present( view() .environment(self) .viewController, animated: animated, completion: completion ) } public func alert( title: String? = nil, messsage: String? = nil, actions: [UIAlertAction] = [], animated: Bool = true, completion: (() -> Void)? = nil, preferredStyle: UIAlertController.Style = .alert ) { let alertController = UIAlertController(title: title, message: messsage, preferredStyle: preferredStyle) actions.forEach { alertController.addAction($0) } self.present(alertController, animated: animated, completion: completion) } }
内容的提问来源于stack exchange,提问作者Blacksmith
相关产品推荐
相关产品推荐

