Search code examples
iosswiftswiftuiuitapgesturerecognizer

How to use tap gesture to offset an image or shape view


I'm trying to use SwiftUI to make it so that if I tap a circle, or image, or something of the sort, it will be offset to a certain location, and if I tap again, it will go back to the location, and toggle back and forwards likewise. I found a tutorial that taught me how to toggle a background color. https://www.ioscreator.com/tutorials/swiftui-gesture-tutorial. If you didn't bother to read it, essentially the code is like this:

struct ContentView: View {
    // 1.
    @State private var didTap: Bool = false

    var body: some View {
        // 2.
        Text("Tap me")
            .frame(minWidth:0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
            // 3.
            .gesture(TapGesture()
                .onEnded {
                    self.didTap.toggle()
                }
            )
            // 4.
            .background(didTap ? Color.blue : Color.red)
    }
}

I changed the

Text("Tap me")
    .frame(minWidth:0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)

to

Circle()
    .frame(width: 100, height: 100)
    .foregroundColor(Color.red)

I was wondering if there was a way to make it so instead of the .background(didTap ? Color.blue : Color.red) I could incorporate the TapGesture boolean variable into a .offset(x: __, y: __) somehow.


Solution

  • I hope this is the solution you are looking for, also I have changed the way you are adding tap gesture.

    struct TestView: View {
        @State private var didTap: Bool = false
    
        private var xOffset: CGFloat {
            return didTap ? 10.0 : 0.0
        }
    
        var body: some View {
            // 2.
            Circle()
                .frame(width: 100, height: 100)
                .foregroundColor(Color.red)
                .onTapGesture {
                    self.didTap.toggle()
            }
                //The x-offset depends on didTap State
                .offset(x: xOffset, y: 0.0)
        }}