【发布时间】:2021-12-20 15:46:21
【问题描述】:
我有以下代码:
struct ContentView: View {
@State var progress:Float = 0.3
var body: some View {
ASlider(progress: $progress)
.frame(width: 300, height: 40)
}
}
struct ASlider: View {
@Binding var progress: Float
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
Rectangle()
.foregroundColor(.gray)
Rectangle()
.foregroundColor(.blue)
.frame(width: geometry.size.width * CGFloat(progress / 1))
}
.cornerRadius(12)
.contentShape(Rectangle()) <<<---- still detects touches outside the bounds...
.gesture(DragGesture(minimumDistance: 0)
.onChanged({ value in
print("Touch: \(value)")
progress = min(max(0, Float(value.location.x / geometry.size.width * 1)), 1)
}))
}
.border(.green)
}
}
我不明白为什么在 ZStack 边界之外检测到手势。
日志显示如下:
触摸:值(时间:2001-01-04 15:55:29 +0000,位置:(67.0, -12.333338419596316),startLocation:(130.3333282470703,-11.333338419596316),速度:SwiftUI._Velocity<__c.cgsize>(valuePerSecond:(-133.40537913839276, 10.334994031205905)))
如您所见,该位置确实检测到 Y 的负值,例如当点击滑块上方而不是内部时。
为什么在添加手势的视图边界之外检测到手势?
【问题讨论】:
-
您可以在边框之前添加
.contentShape(Rectangle())以尽量减少这种影响,但无论如何它会通过点(手指圈)而不是指针点来检测触摸。 -
有趣,所以,这在任何地方都有记录吗?我现在试试内容形状,看看我做了什么。
-
我厌倦了使用
.contentShape(Rectangle()),没有运气。