Rectangle change size by swipe

Hi,, How can I make a rectangle become taller as I swipe down on my trackpad?"


struct BlueRectangleView: View {
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.blue)
                .frame(width: 200, height: 100)
                .cornerRadius(10)
                .shadow(radius: 5)
                .padding()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
    }
}

struct BlueRectangleView_Previews: PreviewProvider {
    static var previews: some View {
        BlueRectangleView()
    }
}

Declare state var for rectangle width and height.

Use this var in the .frame()

Change the values when you swipe.

Here is a code example:

struct BlueRectangleView: View {
    
    @State var height: CGFloat = 100
    @State var width: CGFloat = 200 // If you also want to change width

    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.blue)
                .frame(width: width, height: height)
                .cornerRadius(10)
                .shadow(radius: 5)
                .padding()
                .gesture(
                    DragGesture(minimumDistance: 5)
                        .onChanged { value in
                            let newHeight = height + value.translation.height / 20  // /20: To slow down change
                            let newWidth = width + value.translation.width / 20  // /20: To slow down change
                            if newHeight > 5 && newHeight < 500 {
                                height = newHeight
                                print("New height\(height)")
                            }
                            if newWidth > 5 && newWidth < 400 {
                                width = newWidth
                                print("New width\(width)")
                            }
                        }
                )
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
    }
}

There is no gesture that corresponds to scrolling / panning or Swipe in SwiftUI. If you'd like us to consider adding the necessary functionality, please file an enhancement request using Feedback Assistant. Once you file the request, please post the FB number here.

If you're not familiar with how to file enhancement requests, take a look at Bug Reporting: How and Why?

As an alternative, you could use UISwipeGestureRecognizer + UIViewRepresentable or UIPanGestureRecognizer and wrap your UIKit View which would allow you integrate that into your SwiftUI view.

See Handling pan gestures and Handling swipe gestures to learn about how you could implement those gestures in UIKit

Rectangle change size by swipe
 
 
Q