swiftui中几个常用的手势控制单击点击,双击和长按事件

1,083 阅读1分钟

简单做了一个示例代码,包含三个圆形形状,配置了不同的事件,示例代码:

//
//  RouterView.swift
//  SwiftBook
//
//  Created by song on 2024/7/4.
//

import SwiftUI

struct RouterView: View {
    @State var isClick = false

    var body: some View {
        Circle()
            .foregroundColor(isClick ? .orange : .blue)
            .overlay(content: {
                Text("点击一次")
                    .foregroundStyle(.white)
                    .fontWeight(.heavy)
            })
            .onTapGesture {
                isClick.toggle()
            }
        Circle()
            .foregroundColor(isClick ? .orange : .blue)
            .overlay(content: {
                Text("点击两次")
                    .foregroundStyle(.white)
                    .fontWeight(.heavy)
            })
            .onTapGesture(count: 2) {
                isClick.toggle()
            }
        Circle()
            .foregroundColor(isClick ? .orange : .blue)
            .overlay(content: {
                Text("长按触发")
                    .foregroundStyle(.white)
                    .fontWeight(.heavy)
            })
            .onLongPressGesture(perform: {
                isClick.toggle()
            })
    }
}

#Preview {
    RouterView()
}

可以单击或者双击或者长按触发,其中双击或者多次点击可以通过count来配置,onLongPressGesture也可以配置触发时间和长按时间等属性: