出乎意料的是,SwiftUI的推入视图会在过渡时临时为隐藏的NavigationBar的空间呈现其内容。片刻之后,它重新正确渲染。如何防止这种行为?
要进行GIF屏幕录制,请单击下面的图像。
ContentView.swift
import SwiftUI
struct ContentView: View {
@State var goToNextView = false
var body: some View {
NavigationView { ZStack {
/*@START_MENU_TOKEN@*/Color.yellow/*@END_MENU_TOKEN@*/.edgesIgnoringSafeArea(.all)
NavigationLink(destination: SecondView(), isActive: $goToNextView) {Text("")}
.navigationBarTitle("")
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
VStack {
Button(action: {
print("Button clicked")
self.goToNextView = true
}) { Text("Go to second view") }
.padding()
Text("This is the first view.")
}
}
.foregroundColor(Color.blue)
}
}
}
SecondView.swift
struct SecondView: View {
var body: some View {
ZStack {
Color.purple
.edgesIgnoringSafeArea(.all)
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
VStack { Text("Pushed view") }
}
.foregroundColor(Color.white)
}
}
答案 0 :(得分:2)
我通过使用受this answer影响的视图修改器来消除了此行为。
内嵌评论说明了我所做的更改。
import SwiftUI
struct ContentView: View {
@State var goToNextView = false
var body: some View {
NavigationView { ZStack {
/*@START_MENU_TOKEN@*/Color.yellow/*@END_MENU_TOKEN@*/.edgesIgnoringSafeArea(.all)
NavigationLink(destination: SecondView(), isActive: $goToNextView) {Text("")}
// Removed all nav config code here
VStack {
Button(action: {
print("Button clicked")
self.goToNextView = true
}) { Text("Go to second view") }
.padding()
Text("This is the first view.")
}
}
// Added this to hide bar
.hiddenNavigationBarStyle()
.foregroundColor(Color.blue)
}
}
}
struct SecondView: View {
var body: some View {
ZStack {
Color.purple
.edgesIgnoringSafeArea(.all)
// Added this to hide bar
.hiddenNavigationBarStyle()
VStack { Text("Pushed view") }
}
.foregroundColor(Color.white)
}
}
这是从先前的答案中提取的视图修改器:
struct HiddenNavigationBar: ViewModifier {
func body(content: Content) -> some View {
content
.navigationBarTitle("", displayMode: .inline)
.navigationBarHidden(true)
}
}
extension View {
func hiddenNavigationBarStyle() -> some View {
ModifiedContent(content: self, modifier: HiddenNavigationBar())
}
}
答案 1 :(得分:1)
即使您要隐藏导航栏,SwiftUI仍需要设置NavigationBar标题。在您的第一个视图中,您是这样做的。在第二个你没有。
将此内容添加到SecondView中可解决此问题:
.navigationBarTitle("")
总共SecondView:
struct SecondView: View {
var body: some View {
ZStack {
Color.purple
.edgesIgnoringSafeArea(.all)
.navigationBarTitle("")
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
VStack { Text("Pushed view") }
}
.foregroundColor(Color.white)
}
}