【发布时间】:2020-11-12 21:27:30
【问题描述】:
我正在尝试使视图仅在其剪辑容器视图中可拖动和/或可缩放(否则它可能会遇到并与其他视图的手势冲突),但到目前为止我没有尝试过阻止手势扩展在容器的可见边界之外。
这是我不想要的行为的简化演示......
当红色 Rectangle 部分超出绿色 VStack 区域(被剪裁)时,它会响应超出绿色区域的拖动手势:
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
@State var position: CGPoint = CGPoint(x: 100, y: 150)
@State var lastPosition: CGPoint = CGPoint(x: 100, y: 150)
var body: some View {
let drag = DragGesture()
.onChanged {
self.position = CGPoint(x: $0.translation.width + self.lastPosition.x, y: $0.translation.height + self.lastPosition.y)
}
.onEnded {_ in
self.lastPosition = self.position
}
return VStack {
Rectangle().foregroundColor(.red)
.frame(width: 150, height: 150)
.position(self.position)
.gesture(drag)
.clipped()
}
.background(Color.green)
.frame(width: 200, height: 300)
}
}
PlaygroundPage.current.setLiveView(ContentView())
你会如何限制这个手势只在容器内工作(上例中的绿色区域)?
更新: @Asperi 对上述问题的解决方案效果很好,但是当我在上面的容器旁边添加第二个可拖动容器时,我在第一个容器中得到一个“死区”,我无法在其中拖动(它似乎是第二个正方形的位置如果它没有被剪裁,将覆盖第一个)。问题只发生在原始/左侧,而不是新的。我认为这与它具有更高的优先级有关,因为它被排在第二位。
这是新问题的插图:
这是更新后的代码:
struct ContentView: View {
@State var position1: CGPoint = CGPoint(x: 100, y: 150)
@State var lastPosition1: CGPoint = CGPoint(x: 100, y: 150)
let dragArea1: CGRect = CGRect(x: 0, y: 0, width: 200, height: 300)
@State var position2: CGPoint = CGPoint(x: 100, y: 150)
@State var lastPosition2: CGPoint = CGPoint(x: 100, y: 150)
let dragArea2: CGRect = CGRect(x: 0, y: 0, width: 200, height: 300)
var body: some View {
let drag1 = DragGesture(coordinateSpace: .named("dragArea1"))
.onChanged {
guard self.dragArea1.contains($0.startLocation) else { return }
self.position1 = CGPoint(x: $0.translation.width + self.lastPosition1.x, y: $0.translation.height + self.lastPosition1.y)
}
.onEnded {_ in
self.lastPosition1 = self.position1
}
let drag2 = DragGesture(coordinateSpace: .named("dragArea2"))
.onChanged {
guard self.dragArea2.contains($0.startLocation) else { return }
self.position2 = CGPoint(x: $0.translation.width + self.lastPosition2.x, y: $0.translation.height + self.lastPosition2.y)
}
.onEnded {_ in
self.lastPosition2 = self.position2
}
return HStack {
VStack {
Rectangle().foregroundColor(.red)
.frame(width: 150, height: 150)
.position(self.position1)
.gesture(drag1)
.clipped()
}
.background(Color.green)
.frame(width: dragArea1.width, height: dragArea1.height)
VStack {
Rectangle().foregroundColor(.blue)
.frame(width: 150, height: 150)
.position(self.position2)
.gesture(drag2)
.clipped()
}
.background(Color.yellow)
.frame(width: dragArea2.width, height: dragArea2.height)
}
}
}
关于如何在任何容器外保持禁用拖动的任何想法,如已经实现的那样,但也允许在每个容器的完整范围内拖动,而不管其他容器发生什么?
【问题讨论】:
标签: ios swiftui gesture clipping