在 SwiftUI 中,onTapGesture 是一个手势修饰符,用于检测视图的点击事件并触发指定的操作。它通常用于实现按钮样式的交互或处理简单的点击事件。
基本用法
Text("点击我")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
.onTapGesture {
print("Text 被点击了")
}
效果:点击 Text 时会在控制台打印消息。
解释:onTapGesture 接收一个闭包,闭包里的代码会在用户点击视图时执行。
支持点击次数
可以指定点击的次数,例如单击、双击或多次点击。
Text("双击我")
.padding()
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(10)
.onTapGesture(count: 2) {
print("Text 被双击了")
}
count 参数指定需要几次点击才会触发事件。
效果:只有用户双击 Text,才会触发打印消息。
与其他手势的配合
onTapGesture 可以与其他手势(如拖动、长按)组合使用。
通过 simultaneously(with:) 或 exclusively(before:) 等方法,可以控制手势的优先级。
同时支持点击和拖动
Rectangle()
.fill(Color.blue)
.frame(width: 100, height: 100)
.gesture(
DragGesture()
.onChanged { value in
print("正在拖动:\(value.translation)")
}
)
.onTapGesture {
print("Rectangle 被点击了")
}

优先级控制
如果需要两个手势都触发,可以使用 simultaneously(with:):
Rectangle()
.fill(Color.red)
.frame(width: 100, height: 100)
.gesture(
DragGesture()
.onChanged { _ in print("拖动中") }
.simultaneously(with: TapGesture()
.onEnded { print("点击了") }
)
)
点击显示“点击了”,拖动输出“拖动中”。

示例:按钮切换颜色
通过点击切换视图的背景颜色:
struct ContentView: View {
@State private var isBlue = true
var body: some View {
Rectangle()
.fill(isBlue ? Color.blue : Color.green)
.frame(width: 100, height: 100)
.onTapGesture {
isBlue.toggle() // 点击切换颜色
}
}
}
适用场景
1、处理点击事件:为非按钮视图添加点击操作。
2、支持多种点击次数:例如单击、双击等。
3、组合手势:与拖动、长按等其他手势结合。
注意事项
onTapGesture 的响应范围取决于视图的大小。如果视图尺寸为 0x0 或不可见,手势不会触发。
如果与其他手势冲突,需要通过 exclusively(before:) 或 simultaneously(with:) 明确优先级。
通过 onTapGesture,可以为任意视图快速添加交互功能,使得 SwiftUI 的视图更具动态性和响应性。
