学习目标
- 理解SwiftUI中手势识别器的基本概念。
- 掌握如何使用
onTapGesture处理点击手势。 - 学习如何使用
DragGesture处理拖动手势。 - 掌握如何使用
MagnificationGesture处理缩放手势。 - 掌握如何使用
RotationGesture处理旋转手势。 - 了解手势组合(
simultaneously、sequenced、exclusively)和手势状态。
学习内容
1. 手势识别器基础
SwiftUI通过手势识别器(Gesture Recognizers)来响应用户的交互。你可以将一个或多个手势识别器附加到任何视图上。
2. onTapGesture (点击手势)
用于检测单次或多次点击。
2.1 单次点击
struct TapGestureExample: View {
@State private var message = "Tap me!"
var body: some View {
Text(message)
.font(.largeTitle)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
.onTapGesture {
message = "Tapped!"
}
}
}
2.2 多次点击
struct DoubleTapGestureExample: View {
@State private var tapCount = 0
var body: some View {
Text("Tap Count: \(tapCount)")
.font(.largeTitle)
.padding()
.onTapGesture(count: 2) {
tapCount += 1
}
}
}
3. DragGesture (拖动手势)
用于检测视图的拖动操作,并提供拖动过程中的位置和速度信息。
3.1 基本拖动
struct DragGestureExample: View {
@State private var offset = CGSize.zero
var body: some View {
Circle()

2629

被折叠的 条评论
为什么被折叠?



