探索 SwiftUI 基本手势

前言

SwiftUI 中,我们可以通过添加不同的交互来使我们的应用程序更具交互性,这些交互可以响应我们的点击,点击和滑动。

今天,我们将回顾 SwiftUI 基本手势:

  • TapGesture
  • 长按手势
  • 拖动手势
  • 放大手势
  • 旋转手势

TapGesture

轻击手势使我们能够识别 View 上的一个或多个轻击。
我们有几种方法可以添加点击手势。

第一个是直接使用 .onTapGesture 修饰符。

Circle()
  .onTapGesture {
    // Respond to Tap Gesture 
  }

SwiftUI 文档中使用的其他选项是通过创建手势并将其配置为属性,然后将其与 .gesture(_:include :) 修饰符一起使用。

注意: 为了执行某项操作或响应轻击,我们需要使用 .onEnded 操作关闭,该操作在手势结束时触发。

struct SingleTapGestureView: View {
  var singleTap: some Gesture {
      TapGesture()
          .onEnded { _ in
              // Respond to Tap Gesture
          }
  }

  var body: some View {
      Circle()
          .gesture(singleTap)
  }
}

实际上,我更喜欢第二种方法,因为这样我们可以创建不同的手势并通过我们的代码重复使用它们。

因此,如果我们将代码放在一起,就可以开始编写类似的东西。

giphy.gif

struct TapGestureView: View {
    @State private var isAnimating = false
    @State private var tapped1x = 0

    var singleTap: some Gesture {
        TapGesture()
            .onEnded { _ in
                tapped1x += 1

                withAnimation(Animation.easeOut(duration: 0.5)) {
                    self.isAnimating = true
                }

                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    self.isAnimating = false
                }
            }
    }

    var body: some View {
        VStack {
            Text("Tapped 1X: \(tapped1x) times")
                .font(.caption)

            Circle()
                .frame(width: 80, height: 80)
                .foregroundColor(.orange)
                .overlay(
                    Text("1X")
                        .fontWeight(.medium)
                )
                .background(
                    Circle()
                        .strokeBorder(Color.blue, lineWidth: 3)
                        .scaleEffect(isAnimating ? 1.5 : 1)
                        .opacity(isAnimating ? 0 : 1)
                )
                .gesture(singleTap)
        }
    }
}

类似地,我们只需使用 TapGesture(count:Int) 初始化程序就可以控制要响应的数量。

在这种情况下,您需要点击3次才能触发 .onEnded 操作关闭。

2.gif

struct TapGesture3xView: View {
    @State private var isAnimating = false
    @State private var tapped3x = 0

    var multipleTap: some Gesture {
        TapGesture(count: 3)
            .onEnded { _ in
                tapped3x += 1

                withAnimation(Animation.easeOut(duration: 0.5)) {
                    self.isAnimating = true
                }

                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    self.isAnimating = false
                }
            }
    }

    var body: some View {
        VStack {
            Text("Tapped 3X: \(tapped3x) times")
                .font(.caption)

            Circle()
                .frame(width: 80, height: 80)
                .foregroundColor(.orange)
                .overlay(
                    Text("3X")
                        .fontWeight(.medium)
                )
                .background(
                    Circle()
                        .strokeBorder(Color.blue, lineWidth: 3)
                        .scaleEffect(isAnimating ? 1.5 : 1)
                        .opacity(isAnimating ? 0 : 1)
                )
                .gesture(multipleTap)
        }
    }
}

长按手势

长按手势可让我们在用户长按定义的时间后以及在用户长按的时间内执行操作。

我们可以设置一个最小持续时间,以识别我们的长按手势。 可以在 LongPressGesture 初始化程序中进行设置。

LongPressGesture(minimumDuration: 2)

然后,我们可以使用 .updating 方法在长按期间执行操作,并使用 .onEnded 在识别到我们的手势时执行操作。

在此示例中,我将在长按操作期间更新 Circle() 的大小和颜色,并且当识别出手势时,我将显示“文本已完成”。

另外,我在这里使用的是 GestureState 属性包装器,该包装器在长按期间设置为 true ,在手势结束时设置为 false 。 我正在将此属性包装器用于示例动画。

3.gif

struct LongPressGestureView: View {
    @GestureState private var isLongPressDetected = false
    @State private var isDone = false

    var longPress: some Gesture {
        LongPressGesture(minimumDuration: 2)
            .updating($isLongPressDetected) { currentState, gestureState, transaction in
                DispatchQueue.main.async {
                    isDone = false
                }
                gestureState = currentState
                transaction.animation = Animation.easeIn(duration: 2)
            }
            .onEnded { done in
                isDone = done
            }
    }

    var body: some View {
        VStack {
            Spacer()

            Circle()
                .frame(width: 10, height: 10)
                .foregroundColor(isLongPressDetected ? .orange : .primary)
                .scaleEffect(CGSize(
                                width: isLongPressDetected ? 10 : 1,
                                height: isLongPressDetected ? 10 : 1))

            Spacer()
            if isLongPressDetected {
                Text("Updating...")
            }

            if isDone {
                Text("Done")
            }

            Spacer()

            Text("Long Press 2 sec")
                .padding()
                .background(isLongPressDetected ? Color.green : Color.orange)
                .cornerRadius(16)
                .gesture(longPress)
        }
    }
}

拖动手势

拖动手势允许我们在拖动视图时执行操作。

我们可以利用并使用 .onChanged.onEnded 关闭方法来执行某些操作。 这两种方法都为我们提供了出色的属性 DragGesture.Value,该属性存储以下拖动动作信息:

  • location
  • predictedEndLocation
  • predictedEndTranslation
  • startLocation
  • time
  • translation

我们可以使用该属性来创建可移动视图。 在当前示例中,我使用 .onChanged 方法更新 Circle() 位置坐标。

4.gif

struct DragGestureView: View {
    @State private var location: CGPoint = CGPoint(x: 100, y: 100)

    var drag: some Gesture {
        DragGesture(minimumDistance: 1, coordinateSpace: .local)
            .onChanged { value in
                location = value.location
            }
    }

    var body: some View {
        Circle()
            .frame(width: 100, height: 100)
            .foregroundColor(.orange)
            .position(location)
            .gesture(drag)
    }
}

在这里,添加了 .onEnded 方法,以在拖动结束后重置 Circle() 位置坐标。

struct DragGestureView: View {
    @State private var location: CGPoint = CGPoint(x: 100, y: 100)

    var drag: some Gesture {
        DragGesture(minimumDistance: 1, coordinateSpace: .local)
            .onChanged { value in
                location = value.location
            }
            .onEnded { value in
                withAnimation(.easeOut) {
                    location = CGPoint(x: 100, y: 100)
                }
            }
    }

    var body: some View {
        Circle()
            .frame(width: 100, height: 100)
            .foregroundColor(.orange)
            .position(location)
            .gesture(drag)
    }
}

放大手势

当我们在View上应用放大动作时,放大手势允许做出一些动作。

在这里,还有 .onChanged.onEnded 闭包,我们可以使用它们来在放大动作期间或结束时进行响应。 作为属性,接收到的是 CGFloatMagnificationGesture.Value 。 我们可以以此为例来更改视图大小。

struct MagnificationGestureView: View {
    @State var magnifiedValue: CGFloat = 1.0

    var magnification: some Gesture {
        MagnificationGesture()
            .onChanged { value in
                magnifiedValue = value
            }
            .onEnded { value in
                magnifiedValue = 1.0
            }
    }

    var body: some View {
        Circle()
            .frame(width: 100 * magnifiedValue, height: 100 * magnifiedValue)
            .foregroundColor(.orange)
            .gesture(magnification)
            .animation(.easeOut)
    }
}

旋转手势

旋转手势允许旋转视图,并在旋转过程中和旋转结束时以某些动作做出响应。

它还为我们提供了 .onChanged.onEnded 闭包,这些闭包为我们提供了 RotationGesture.Value,它表示手势 Angle 值。 我们可以使用该值旋转视图。

struct RotationGestureView: View {
    @State private var angle = Angle(degrees: 0.0)
    @State private var backgroundAngle = Angle(degrees: 0.0)

    var rotation: some Gesture {
        RotationGesture()
            .onChanged { angle in
                self.angle = angle
            }
            .onEnded { angle in
                withAnimation(Animation.spring()) {
                    self.backgroundAngle = angle
                }
            }
    }

    var body: some View {
        Rectangle()
            .frame(width: 150, height: 150, alignment: .center)
            .foregroundColor(.orange)
            .rotationEffect(self.angle)
            .gesture(rotation)
            .background(
                Rectangle()
                    .shadow(color: .primary, radius: 10, x: 0.0, y: 0.01)
                    .foregroundColor(.secondary)
                    .rotationEffect(backgroundAngle)
            )
    }
}

总结

上面是对 SwiftUI 基本手势的总结。我们可以实现更多的交互使我们的 App 变得更生动。

对于高级的使用,可以将手势组合或者同时使用以做出响应,或者可以实现自己的自定义手势。

关注我们

我们的愿景是希望更多的人学习和使用Swift,我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术干货

本文已在公众号「Swift 社区」发布,如需转载请加微信:fzhanfei,备注转载开白

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

网罗开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值