Search code examples
iosswiftswiftuigesturedraggesture

How to restrict drag gesture to particular frame only in swiftUI


I want to drag circle shape only within a frame horizontal. I try below code you can see shape work perfectly horizontal and also left side but when drag right side shape drag up to out of device frame. I check so many answer but did't work anything. also try to add .onEnded but don't work. please help me thanks in advance here is a code that i tried

struct ProgressIndicator: View {
    @State private var position = CGSize.zero
    var body: some View {
        GeometryReader { geometry in
            VStack(alignment: .leading) {
                ZStack {
                    Circle()
                        .foregroundColor(Color.blue)
                        .opacity(0.3)
                        .frame(width: 40, height: 40, alignment: .leading)
                        .padding(.bottom, -12)
                }
                .gesture(
                     DragGesture()
                    .onChanged({ (value) in
                            self.position.width += value.location.x
                    })
                )
                .offset(x: self.position.width - 20, y: 0)
            }
        }
    }
} 

here is screenshot of circle shape for drag to left and right enter image description here enter image description here


Solution

  • You can restrict the position with GeometryReader:

    self.position.width = min(self.position.width + value.location.x, geometry.size.width / 2)
    

    Here's the result from Playgrounds:

    https://i.sstatic.net/AgF1a.jpg