将UITimer值返回到mapView-Swift

问题描述

当我单击UIButton时,@IBAction func pressplay()启动,它使用计时器使滑块的拇指(UiSlider)每秒移动一次。 滑块的初始值为0。

class MapViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate,SCSEarthquakesHandler,SCSPublicSeismometersHandler
{
    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet var sliderTime: UiSlider!

    @IBAction func pressplay(_ sender: Any)
    {
         let calendar2 = Calendar.current
        let today = Date()
        var cnt = Int(sliderTime.value)
        let play = UIImage(named: "play")
        let pause = UIImage(named: "pause")
        let format = DateFormatter()
        playButton.setimage(play,for: .normal)
        if control == true && Int(sliderTime.value) < 0
        { //set to play
            control = false
            playButton.setimage(pause,for: .normal)
            if Int(sliderTime.value) < 0
            {
                timer = Timer.scheduledTimer(withTimeInterval: 1,repeats: true)
                { [self]t in //ogni secondo questo timer cambia il valore dell'alpha del pin che sta vibrando
                    
                    if cnt < 0
                    {
                        cnt = Int(self.sliderTime.value)
                        self.sliderTime.value += 1
                        let newDate2 = calendar2.date(byAdding: .day,value: Int(self.sliderTime.value),to:today)! //sottraggo alla data attuale il vlaore dello slider per tornare indietro nel tempo
                        format.dateStyle = .medium // "MM/GG/AAAA"
                        self.labelTime.text = "\(format.string(from: newDate2))"
                    }else if cnt == 0{
                        removeSeismometers = false
                        playButton.setimage(play,for: .normal)
                        timer!.invalidate()
                    }
                }
            }
        }else if control == false && Int(sliderTime.value) < 0 { //mette in pausa
            removeSeismometers = true
            playButton.setimage(play,for: .normal)
            control = true
            timer!.invalidate()
        }
    }
func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView?
    {
        print(Int(sliderTime.value))
     ...
    }

}

我试图调出func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {内滑块的值,但是尽管滑块没有值0,但是当我在此处打印它时,它总是返回值0。为什么? 我尝试了一些事情……我定义了一个全局变量并将其初始化为0。我在mapView(...)函数调用了该变量,并将其增加了1。我注意到它每秒增加一次(减一秒钟)。所以我不明白为什么sliderTime.value不会将当前值返回给我,而是总是返回0。 如何在此动画期间打印滑块的值?

解决方法

首先,您不应该使用滑块来存储值。 (查看对象显示信息,而不是保存信息。)您应该在您的类中设置一个实例变量,并在该实例变量上添加didSet方法,以使滑块滑动。

第二,如果将变量cnt设置为0,它将永远不会递增。您的计时器的关闭包含if语句if cnt < 0。如果使用cnt == 0,那将永远是不正确的。您需要将该if语句更改为if cnt <= 0。如果cnt为零或更小,这将是您想要的。