我想使用 UINavigationController 和 SwiftUI 应用程序生命周期进行一些实验
我创建了一个名为 JDNavigationController 的自定义导航控制器。除了具有
@Observable
宏 之外,它没有做太多事情
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")
}
}
}
}
我已经尝试过了
hostingController.view.insetsLayoutMarginsFromSafeArea = false
似乎没有一个有效。
我打开了视图调试器,看起来白色部分来自 UIHosting 控制器,但我不确定如何修复它。
编辑:有关设置的附加信息。
我为 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)
}
}
这比我想象的要简单得多..
YourCustomNavigationControllerView {
ContentView()
}
.ignoresSafeArea() // <- here