I want to put a "Scan" button on the same Form row as my Picker. The scanner View has its own NavigationLink that should pop up when the user taps the Scan button.
What actually happens:
Both the Picker's NavigationLink and the Scanner's NavigationLink destination views appear at the same time. When you tap either the Picker or the Scan button, you will randomly see one of the two destinations (assuming one is above the other in z-order).
Here is what it will look like:
Here is the code to reproduce this issue...
struct Truck: Hashable, Identifiable {
var id: String
var color: String
var assetId: String
}
struct ContentView: View
{
var trucks = [
Truck(id: "a", color: "Red", assetId: "1"),
Truck(id: "b", color: "Green", assetId: "2"),
Truck(id: "c", color: "Blue", assetId: "3")
]
@State private var myTruck: Truck?
var body: some View {
GeometryReader { geometry in
NavigationView {
Form {
HStack {
Picker("Choose a truck", selection: $myTruck) {
ForEach(trucks) { truck in
Text(truck.color).tag(Optional.some(truck.self))
}
}
.frame(maxWidth: (geometry.size.width * 0.5))
.clipped()
Scanner(callback: { barcode in
myTruck = trucks.filter { $0.assetId == barcode }.first
})
}
}
}
}
}
}
struct Scanner: View {
@State private var isShowingScanner: Bool = false
var callback: (String)->()
var body: some View {
ZStack { // makes NavigationLink not visible.
NavigationLink(destination: Button("Scan 3 example", action: {
callback("3")
self.isShowingScanner = false
}), isActive: $isShowingScanner) {
EmptyView()
}
.frame(width: 0, height: 0)
Button("Scan", action: {
isShowingScanner = true
})
}
}
}
What I want to happen is if you tap the picker the list of options appears. If you tap the scan button the scanner window should appear. I thought about using tags for the various destination views, but I don't know how to do that on the Picker's destination. Also, the scanner is a separate component, so I thought it would be able to control its own NavigationLink.
XCode 12.3
Swift 5
iOS 14.3
question from:
https://stackoverflow.com/questions/65836170/swiftui-how-can-i-navigate-to-a-navigationlink-when-there-is-a-picker-on-the-sa 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…