0

我正在尝试将 DragGesture 用于我的侧边菜单。目前,DragGesture 正在使用整个屏幕,我只想从左到右使用它,如屏幕截图所示(灰色区域):

我的代码片段:

@State var width = UIScreen.main.bounds.width - 65
@State var x = -UIScreen.main.bounds.width + 65

var body: some View {
    
    ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)) {
        HomePage(x: $x)
        SlideMenu()
            .shadow(color: Color.black.opacity(x == 0 ? 0.2 : 0), radius: 5, x: 5, y:0)
            .offset(x: x)
            .background(Color.gray.opacity(x == 0 ? 0.2 : 0).ignoresSafeArea(.all, edges: .vertical).onTapGesture {
                withAnimation {
                    
                    x = -width
                }
            })
    }
    .gesture(DragGesture().onChanged({ (value) in
        withAnimation {
            if value.translation.width > 0 {
                if x < 0 {
                    x = -width + value.translation.width
                }
            }
            else {
                x = value.translation.width
            }
        }
    }).onEnded({ (value) in
        withAnimation {
            if -x < width / 2 {
            x = 0
            }
            else {
                x = -width
            }
        }
    }))
}
4

1 回答 1

0

您可以检查手势startLocation并忽略它,如果它超出您想要的矩形

struct ContentView: View {
    @State var width = UIScreen.main.bounds.width - 65
    @State var x = -UIScreen.main.bounds.width + 65
    let gestureMaxScreenOffset: CGFloat = 100

    var body: some View {
        ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)) {
            Text("HomePage(x: $x)")
                .onTapGesture {
                    print("hello")
                }
            Text("SlideMenu()")
                .fillMaxSize()
                .shadow(color: Color.black.opacity(x == 0 ? 0.2 : 0), radius: 5, x: 5, y: 0)
                .offset(x: x)
                .background(Color.gray.opacity(x == 0 ? 0.2 : 0).ignoresSafeArea(.all, edges: .vertical).onTapGesture {
                    withAnimation {

                        x = -width
                    }
                })
        }.gesture(DragGesture().onChanged({ (value) in
            withAnimation {
                if value.startLocation.x > gestureMaxScreenOffset {
                    return
                }
                if value.translation.width > 0 {
                    if x < 0 {
                        x = -width + value.translation.width
                    }
                } else {
                    x = value.translation.width
                }
            }
        }).onEnded({ (value) in
            if value.startLocation.x > gestureMaxScreenOffset {
                return
            }
            withAnimation {
                if -x < width / 2 {
                    x = 0
                } else {
                    x = -width
                }
            }
        }))
    }
}
于 2021-09-01T11:18:26.073 回答