问题
As it's common practice to use, I have LazyVStack inside my scroll View.
I have 3 views.
1st view contains Header which can be shown or hidden, and all other content goes under the header
2nd view with button to present 3rd view (when 3rd view is presented I want header to disappear, it does, but there is blank space under, and when I come back to previous view with mode.wrappedValue.dismiss() it's lifted and I cannot access the last image from 2nd view.
My repo: https://github.com/martynasNarijauskas/swiftui My code:
import SwiftUI
struct MainView: View {
var body: some View {
TestView()
}
}
struct TestView: View {
let hideUserInfo = NotificationCenter.default
.publisher(for: NSNotification.Name("HideUserInfo"))
let showUserInfo = NotificationCenter.default
.publisher(for: NSNotification.Name("ShowUserInfo"))
@State
var shouldShowHeader = true
@State
var selection: Int? = 0
var body: some View {
ZStack {
VStack {
if shouldShowHeader {
Text("Test")
}
NavigationView {
ZStack {
Color.green.ignoresSafeArea()
VStack {
NavigationLink(
destination: TestView2(),
tag: 1,
selection: $selection,
label: {
EmptyView()
})
Button(
action: {
selection = 1
},
label: {
Text("Button")
}
)
}
}
.navigationBarHidden(true)
.navigationBarTitle("", displayMode: .inline)
}
}
}.onReceive(hideUserInfo) { info in
self.shouldShowHeader = false
}
.onReceive(showUserInfo) { info in
self.shouldShowHeader = true
}
}
}
struct TestView2: View {
@State
var selection: Int? = 0
var body: some View {
ZStack {
Color.green.ignoresSafeArea()
ScrollView {
NavigationLink(
destination: OpenedView(),
tag: 1,
selection: $selection,
label: {
EmptyView()
})
Button(
action: {
selection = 1
},
label: {
Text("Button")
}
)
LazyVStack {
Image(systemName: "star").resizable().frame(width: 100, height: 100)
Image(systemName: "star").resizable().frame(width: 100, height: 100)
Image(systemName: "star").resizable().frame(width: 100, height: 100)
Image(systemName: "star").resizable().frame(width: 100, height: 100)
Image(systemName: "star").resizable().frame(width: 100, height: 100)
Image(systemName: "star").resizable().frame(width: 100, height: 100)
Image(systemName: "star").resizable().frame(width: 100, height: 100)
Image(systemName: "star").resizable().frame(width: 100, height: 100)
}
}
}
.onAppear {
NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "ShowUserInfo")))
}
.navigationBarHidden(true)
.navigationBarTitle("", displayMode: .inline)
}
}
struct OpenedView: View {
@Environment(\.presentationMode)
var mode: Binding<PresentationMode>
@State
var selection: Int? = 0
var body: some View {
VStack {
Button(
action: {
mode.wrappedValue.dismiss()
},
label: {
Text("Go bck")
}
)
}.onAppear {
NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "HideUserInfo")))
}
.navigationBarHidden(true)
.navigationBarTitle("")
}
}
来源:https://stackoverflow.com/questions/65480805/swiftui-mode-wrapped-value-lifts-scrollview