简体   繁体   中英

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在此处输入图像描述 在此处输入图像描述

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://imgur.com/FA5xyAz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM