ios - 如何制作 SwiftUI 手势以在按下 View 时保持运行代码

标签 ios swift swiftui

我正在尝试制作一个控制计数器的按钮。如果你点击它,计数器会加一。但是如果你点击并按住它,我希望计数器在你按住它的同时每 n 秒增加一个,并一直这样做直到你放手。

如果我使用如下代码:

@GestureState var isDetectingLongPress = false
var plusLongPress: some Gesture {
    LongPressGesture(minimumDuration: 1)
        .updating($isDetectingLongPress) { currentstate, gestureState, _ in
            gestureState = currentstate
        }
        .onEnded { finished in
            print("LP: finished \(finished)")
        }
}

然后isDetectingLongPress一秒钟后变为真,然后立即变为假。以及 onEnded 中的打印1秒后也被调用。

我想要一些方法来保持调用代码以在手指按下 View 时不断更新计数器 - 而不仅仅是在检测到长按后一次。

最佳答案

改用以下组合来跟踪连续按下

使用 Xcode 11.4/iOS 13.4 测试

@GestureState var isLongPress = false // will be true till tap hold

var plusLongPress: some Gesture {
    LongPressGesture(minimumDuration: 1).sequenced(before:   
          DragGesture(minimumDistance: 0, coordinateSpace: 
          .local)).updating($isLongPress) { value, state, transaction in
            switch value {
                case .second(true, nil):
                    state = true
                   // side effect here if needed
                default:
                    break
            }
        }
}

关于ios - 如何制作 SwiftUI 手势以在按下 View 时保持运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61523374/

相关文章:

ios - 检测有问题的数组( Debug模式)

iphone - 应用程序似乎在锁定屏幕后一段时间后退出,这是正常行为吗?

ios - -all_load 其他链接器标志导致第 3 方框架中的重复符号错误

ios - 更改 UIActionSheet 中项目的文本颜色 - iOS 8

swift - 我想使用 SnapKit 将顶部 UIView 放置在 UITableView 之上

ios - 为什么 UITableView 根据其默认 rowheight(44) 而不是自定义 rowHeight 来计算其 contentSize

ios - iOS 上的地理围栏 - Swift

ios - ScrollView 内的 SwiftUI 列表

swiftui - Xcode 11.1 SwiftUI 预览失败

ios - UIViewRepresentable.updateUIView(_ :context:) is not called when @State, @Binding 或 @EnvironmentObject 已更改