我在上层创建一个带有按钮的列表视图。我想在用户单击NavigationLink之后立即隐藏该按钮,而在详细视图中看不到它。
我通过使用@State var showAddButton
成功实现了该功能,并通过如下所示的onDisappear
和onAppear
操作对其进行了控制,但是如果主视图没有完全消失,则按钮不会消失。
是否有人有其他解决方案来触发其他动作并保持NavigationLink的原始链接动作?
@State var showAddButton = true
var body: some View {
ZStack{
NavigationView{
List{
ForEach(items, id: \.id){ item in
NavigationLink(destination: WorkItemDetailView(item: item)){
WorkItemListRow(item: item)
}.onDisappear{self.showAddButton = false}
.onAppear{self.showAddButton = true}
}
}
.navigationBarTitle("List", displayMode: .inline)
}
if showAddButton {
FloatAddButton()
}
}
}
答案 0 :(得分:0)
如果要将该按钮粘贴到主视图,则可以切换ZStack的位置:
NavigationView{
ZStack{
List{
ForEach(items, id: \.self){ item in
NavigationLink(destination: WorkItemDetailView(item: item)){
WorkItemListRow(item: item)
}
}
}
.navigationBarTitle("List", displayMode: .inline)
Button("mybutton",action: {})}
}
答案 1 :(得分:0)
您也可以使用类似的东西
struct NavigationBlock<Destination: View, Content: View>: View {
@State private var isActive: Bool = false
var destination: Destination
var content: (Binding<Bool>) -> Content
init(destination: Destination, @ViewBuilder content: @escaping (Binding<Bool>) -> Content) {
self.destination = destination
self.content = content
}
var body: some View {
Group {
content($isActive)
NavigationLink(destination: destination,
isActive: $isActive) { Spacer() }.hidden()
}
}
}
用法:
struct ContentView: View {
var body: some View {
NavigationView {
NavigationBlock(destination: Text("Hello")) { binding in
Button(action: {
print("User did tap 'Hello' button")
binding.wrappedValue = true
}) { Text("Hello button") }
}
}
}
}