rifaaQ
rifaaQ

Reputation: 43

On tap gesture on an image SwiftUI

So I am trying to change between views when someone clicks on the image, but the action after the ontapgesture is always "expression is unused". I tried changing it to a navigation view as well as other things but I feel like nothing seems to be working.

Code below:

    struct MenuView2: View {
    @State private var menuu2 = menu2()
    
    var body: some View {
        ScrollView(){
            VStack {
                ZStack {
                    Rectangle().frame(height:40).opacity(0.25).blur(radius: 10).onTapGesture {
                        print("breakfast tapped ")
                    }
                    HStack {
                        VStack(alignment: .leading, spacing: 8, content: {
                            Text("Breakfast").font(.largeTitle)
                        })
                    }
                }
                Image("breakfast").resizable().scaledToFill().onTapGesture {
                    menuu2
                }
            }
            
        }
    }
}

Thank you.

Upvotes: 4

Views: 7619

Answers (1)

The error you get is "correct" in that menuu2 does not do anything, it is just there.

There are a number of ways to change view on tap, this is just one way:

struct MenuView2: View {
    
    @State private var menuu2 = menuu2()
    @State private var changeView = false
    
    var body: some View {
        changeView ? AnyView(theOtherView) : AnyView(theScrollView)
    }
    
    var theOtherView: some View {
        // menuu2 presumably
        // just for testing
        Text("theOtherView").onTapGesture {
            self.changeView = false
        }
    }
    
    var theScrollView: some View {
        ScrollView() {
            VStack {
                ZStack {
                    Rectangle().frame(height:40).opacity(0.25).blur(radius: 10).onTapGesture {
                        print("breakfast tapped ")
                    }
                    HStack {
                        VStack(alignment: .leading, spacing: 8, content: {
                            Text("Breakfast").font(.largeTitle)
                        })
                    }
                }
                Image("breakfast").resizable().scaledToFill().onTapGesture {
                    self.changeView = true
                }
            }
        }
    }
}

Upvotes: 5

Related Questions