Reputation: 39
I have 3 buttons in my view. I want to change view with navigationlink when 2 buttons are active. When I tap to tap1 and tap3 I want to go to ViewOne(), when I tap to tap2 and tap3 I want to ViewTwo() How can I do that ?
@State var tap1 : Bool = false
@State var tap2 : Bool = false
@State var tap3 : Bool = false
NavigationLink(destination: ViewOne(), isActive: $tap1, label: {
VStack{
Image("smile")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 90)
Text("Fine")
.font(.system(size: 50, weight: .thin))
.padding(.bottom, 30)
}
NavigationLink(destination: ViewTwo(), isActive: $tap2) {
VStack{
Image("sad")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 90)
Text("Bad")
.font(.system(size: 50, weight: .thin))
.padding(.bottom, 30)
}
NavigationLink(destination: ?(), isActive: $tap3) {
Text("Continue")
Upvotes: 1
Views: 833
Reputation: 54426
You can try the following:
struct ContentView: View {
@State var tap1: Bool = false
@State var tap2: Bool = false
@State var isLinkActive: Bool = false
var body: some View {
NavigationView {
VStack {
button1
button2
button3
}
}
}
var button1: some View {
Button(action: {
self.tap1.toggle()
}) {
VStack {
Image("smile")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 90)
Text("Fine")
.font(.system(size: 50, weight: .thin))
.padding(.bottom, 30)
}
}
.background(tap1 ? Color.green : .clear)
}
var button2: some View {
Button(action: {
self.tap2.toggle()
}) {
VStack {
Image("sad")
.resizable()
.renderingMode(.original)
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 90)
Text("Bad")
.font(.system(size: 50, weight: .thin))
.padding(.bottom, 30)
}
}
.background(tap2 ? Color.red : .clear)
}
var button3: some View {
Button(action: {
// make sure you set the link only when ready
// what should happen if tap1 and tap2 are true?
self.isLinkActive.toggle()
}) {
Text("Continue")
}
.background(
NavigationLink(destination: destinationView, isActive: $isLinkActive) {
EmptyView()
}
.hidden()
)
}
@ViewBuilder
var destinationView: some View {
if tap1 {
Text("ViewOne")
} else if tap2 {
Text("ViewTwo")
}
}
}
Upvotes: 1