开发者社区> 问答> 正文

如何在 SwiftUI 中实现触发开关案例的左或右 DragGesture()?

我在视图中创建了一个"拖动手势",该视图应选择@State(Bool),用户是向左轻扫还是向右滑动。 问题是,只检测到向右滑动。 如何使用 .gesture() 捕获用户在屏幕上向左或向右轻扫?

import SwiftUI

struct SwiftUIView: View {

//MARK: Value to change on swipe gesture @State var swipeRight: Bool

var body: some View { VStack { //MARK: Value displayed after user swiped Text($swipeRight ? "Right" : "Left") } .gesture( DragGesture() .onChanged { (value) in //MARK: What is it missing here? switch value.location.x { case ...(-0.5): self.swipeRight = false print("Swipe Left return false") case 0.5...: self.swipeRight = true print("Swipe Right return true") default: () } }) }

展开
收起
上好佳Hao 2019-11-30 23:29:23 1610 0
1 条回答
写回答
取消 提交回答
  • 您应该比较新旧位置: if value.startLocation.x > value.location.x { print("Swipe Left") } else { print("Swipe Right") } 因此,代码的重构版本将是: struct ContentView: View { enum SwipeHorizontalDirection: String { case left, right, none }

    @State var swipeHorizontalDirection: SwipeHorizontalDirection = .none { didSet { print(swipeHorizontalDirection) } }
    
    var body: some View {
        VStack {
            Text(swipeHorizontalDirection.rawValue)
        }
        .gesture(
            DragGesture()
                .onChanged {
                    if $0.startLocation.x > $0.location.x {
                        self.swipeHorizontalDirection = .left
                    } else if $0.startLocation.x == $0.location.x {
                        self.swipeHorizontalDirection = .none
                    } else {
                        self.swipeHorizontalDirection = .right
                    }
        })
    }
    

    }

    2019-11-30 23:29:39
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载