我在视图中创建了一个"拖动手势",该视图应选择@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: () } }) }
您应该比较新旧位置: 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
}
})
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。