Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On tap gesture on an image SwiftUI

Tags:

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.

like image 702
rifaaQ Avatar asked Sep 02 '25 01:09

rifaaQ


1 Answers

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
                }
            }
        }
    }
}
like image 141
workingdog support Ukraine Avatar answered Sep 05 '25 09:09

workingdog support Ukraine