我想在按钮按下开始时执行一个动作,然后在按钮停止被按下时执行另一个动作。我一开始寻找的是一个简单的解决方案,但却陷入了更复杂的配置中。从BlueSpud得到的一个相当简单且接近的选项是:不使用按钮动作,而是尝试:
struct MyView: View {
@State private var pressing = false
var body: some View {
Text("Button")
.background(self.pressing ? Color.red : Color.blue)
.gesture(DragGesture(minimumDistance: 0.0)
.onChanged { _ in
self.pressing = true
print("Pressing started and/or ongoing")
}
.onEnded { _ in
self.pressing = false
print("Pressing ended")
})
}
}
这段代码的问题在于,如果您在按下按钮时将手指拖出按钮区域,则.onEnded永远不会被调用,而且由于事件没有可靠的结束,解决方案无法正常工作。
我还尝试了苹果关于组合SwiftUI手势的示例。它提供了非常一致的控制压下和未压下状态,但我似乎不知道在哪里插入我的操作:
struct PressedButton: View {
var startAction: ()->Void
var endAction: ()->Void
enum DragState {
case inactive
case pressing
case dragging(translation: CGSize)
var translation: CGSize {
switch self {
case .inactive, .pressing:
return .zero
case .dragging(let translation):
return translation
}
}
var isActive: Bool {
switch self {
case .inactive:
print("DragState inactive but I can't add my action here")
//self.endAction()
return false
case .pressing, .dragging:
return true
}
}
var isDragging: Bool {
switch self {
case .inactive, .pressing:
return false
case .dragging:
return true
}
}
}
@GestureState var dragState = DragState.inactive
var body: some View {
let longPressDrag = LongPressGesture(minimumDuration: 0.1)
.sequenced(before: DragGesture())
.updating($dragState) { value, state, transaction in
switch value {
// Long press begins.
case .first(true):
print("Long press begins. I can add my action here")
self.startAction()
state = .pressing
// Long press confirmed, dragging may begin.
case .second(true, let drag):
//print("Long press dragging")
state = .dragging(translation: drag?.translation ?? .zero)
// Dragging ended or the long press cancelled.
default:
print("Long press inactive but it doesn't get called")
state = .inactive
}
}
.onEnded { _ in
print("Long press ended but it doesn't get called")
}
return Text("Button")
.background(dragState.isActive ? Color.purple : Color.orange)
.gesture(longPressDrag)
}
}