gpt4 book ai didi

ios - 在 MKMapViewDelegate 中执行代码之前设置一个计时器

转载 作者:行者123 更新时间:2023-12-01 18:35:14 25 4
gpt4 key购买 nike

使用 MKMapView,我想捕捉用户完成将 map 移动到另一个区域的时刻,然后在该区域显示注释。

为了捕获他完成移动我使用的 map 的那一刻:

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool){
}

但是,我会在调用委托(delegate)内的代码之前添加 1 秒的时间间隔,以防用户开始移动相机多一点。如果用户在这段时间结束之前再次移动 map ,它当然会取消代码的执行。

有任何想法吗 ?

最佳答案

一种方法是使用 DispatchWorkItem ,一个对象,它封装了一些代码以供以后执行。当用户在 mapView(_:regionWillChangeAnimated:) 中再次开始移动 map View 时,您可以取消工作项。方法:

class YourClass: NSObject, MKMapViewDelegate {
private var userFinishedMovingMapViewWorkItem: DispatchWorkItem?

func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
// Cancel any previous work item
userFinishedMovingMapViewWorkItem?.cancel()
}

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
// Create a new work item, store it in a property, and set it to execute
// on the main queue after one second from now
let workItem = DispatchWorkItem(qos: .userInteractive) {
// Code you want to execute after 1 second
}

userFinishedMovingMapViewWorkItem = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem)
}
}

关于ios - 在 MKMapViewDelegate 中执行代码之前设置一个计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60560377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com