【问题标题】:Multiple actions being performed on Long Press Gesture对长按手势执行多项操作
【发布时间】:2017-09-16 16:10:47
【问题描述】:

我正在尝试在长按时执行一项操作(目前,我只是打印出数据)。但是每当我在模拟器/手机中做长按手势时,它都会重复几次动作。每当激活长按手势时,如何使其仅执行一次该操作?

抱歉,我是 iOS 开发的新手。

这是我的代码:

@IBAction func addRegion(_ sender: Any) {
    guard let longPress = sender as? UILongPressGestureRecognizer else
    { return }
    let touchLocation = longPress.location(in: mapView)
    let coordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView)
    let region = CLCircularRegion(center: coordinate, radius: 50, identifier: "geofence")
    mapView.removeOverlays(mapView.overlays)
    locationManager.startMonitoring(for: region)
    let circle = MKCircle(center: coordinate, radius: region.radius)
    mapView.add(circle)
    print(coordinate.latitude)
    print(coordinate.longitude)

    //returns:
    // 27.4146234860156
    // 123.172249486142
    // ... (a lot of these)
    // 27.4146234860156
    // 123.172249486142

}

【问题讨论】:

    标签: ios swift uilongpressgesturerecogni


    【解决方案1】:

    手势识别器函数以其当前状态多次调用。 如果你想在长按手势被激活时做某事

    您应该对手势状态进行验证,如下所示:

           guard let longPress = sender as? UILongPressGestureRecognizer else
            { return }
    
            if longPress.state == .began { // When gesture activated
    
            }
            else if longPress.state == .changed { // Calls multiple times with updated gesture value 
    
            }
            else if longPress.state == .ended { // When gesture end
    
            }
    

    【讨论】:

    • 如果需要,检查.changed 状态。
    • 你能把它和 UIContextMenuInteraction 结合起来吗?
    • @uuuuuu UIContextMenuInteraction 有自己的手势,不需要添加额外的手势。您可以使用本教程链接kylebashour.com/posts/ios-13-context-menus 实现基本的 UIContextMenuInteraction。
    • @Surjeet 谢谢。我的问题是我需要在实现手势之前进行数据库调用以检查用户的状态(手势是基于 db 调用返回的图像 vc)。是否可以使用.begin,.changed先检查db再返回vc?
    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多