GestureButton 是一个 SwiftUI 按钮,可以使用单个手势触发许多不同的特定于手势的操作。
您可以像使用常规 Button
一样使用 GestureButton
,并且可以为不同的手势定义不同的操作。
struct ContentView: View {
@State private var isPressed = false
var body: some View {
GestureButton(
isPressed: $isPressed,
pressAction: { print("Pressed") },
releaseInsideAction: { print("Released Inside") },
releaseOutsideAction: { print("Released Outside") },
longPressAction: { print("Long Pressed") },
doubleTapAction: { print("Double Tapped") },
repeatAction: { print("Repeating Action") },
dragStartAction: { value in print("Drag Started") },
dragAction: { value in print("Drag \(value)") },
dragEndAction: { value in print("Drag Ended") },
endAction: { print("Gesture Ended") }
) { isPressed in
Color.yellow // You can use any button content view.
}
}
}
您可以传入各种延迟和超时来更改按钮的行为,例如,两次点击之间的最大时间,以便将这些点击计为双击。您可以使用任何 View
作为按钮标签。
可以使用 Swift Package Manager 安装 GestureButton
https://github.com/danielsaidi/GestureButton.git
如上所示,GestureButton
可以像常规 Button
一样使用,但在 ScrollView
中使用时需要一些额外的处理。
在 iOS 17 及更早版本中,您必须将 GestureButtonScrollState
传入 GestureButton
初始化程序,以防止按钮阻止滚动操作。
在 iOS 18 及更高版本中,您必须传入一个 GestureButtonScrollState
并将其应用于滚动视图。
struct ContentView: View {
@StateObject private var scrollState = GestureButtonScrollState()
var body: some View {
ScrollView(.horizontal) {
GestureButton(
scrollState: scrollState,
pressAction: { print("Pressed") },
label: { isPressed in
Color.yellow // You can use any button content view.
}
)
}
.scrollGestureState(scrollState)
}
}
该库的未来版本应致力于简化此设置,仅需要修饰符。手势按钮应作为环境值访问该状态。
在线文档包含更多信息、文章、代码示例等。
该演示应用程序允许您探索该库。要试用它,只需打开并运行 Demo
项目。
您可以在 GitHub Sponsors 上赞助我,或者联系我以获得付费支持,以帮助支持我的开源项目。
您的支持使我有可能投入更多精力到这些项目中,并使它们达到最佳状态。
如果您有任何疑问或想以任何方式做出贡献,请随时与我联系。
GestureButton 在 MIT 许可证下可用。 有关更多信息,请参见 LICENSE 文件。