我正在尝试动态地向安全区域添加额外的填充。为了实现这一点,我编写了将 SwiftUI 视图包装到其中UIHostingController
并对其进行设置additionalSafeAreaInsets
的修饰符:
extension View {
func extendSafeArea() -> some View {
modifier(ExtendedSafeAreaModifier())
}
}
struct ExtendedSafeAreaModifier: ViewModifier {
func body(content: Content) -> some View {
Container(content: content)
.edgesIgnoringSafeArea(.all)
}
private struct Container: UIViewRepresentable {
let content: Content
typealias UIViewType = UIView
func makeUIView(context: Context) -> UIViewType {
let hostingController = UIHostingController(rootView: content)
hostingController.additionalSafeAreaInsets = .init(top: 0, left: 0, bottom: 200, right: 0)
context.coordinator.container = hostingController
return hostingController.view
}
func updateUIView(_ uiView: UIViewType, context: Context) {
uiView.setNeedsLayout()
}
func makeCoordinator() -> Coordinator {
.init()
}
class Coordinator {
var container: UIViewController!
}
}
}
在涉及复杂导航之前,这非常有效:
struct ContentView: View {
@State var tab: Int = 0
var body: some View {
TabView(selection: $tab) {
NavigationView {
ZStack {
Rectangle()
.foregroundColor(.red)
NavigationLink(
"B",
destination: Rectangle()
.foregroundColor(.blue)
.navigationBarTitle("B", displayMode: .inline)
.navigationBarHidden(false)
)
}
.navigationBarHidden(true)
.navigationBarTitle("", displayMode: .inline)
}
.extendSafeArea()
.tag(0)
.tabItem {
Text("A")
}
Text("C")
.tag(1)
.tabItem {
Text("C")
}
}
}
}
在上面的示例中,更改选项卡会导致NavigationView
完全崩溃:
Broken navigation
这种行为可以解决吗?是否有另一种方法来实现扩展安全区域?谢谢。