滑块移动时删除注释-迅速

如何解决滑块移动时删除注释-迅速

我的注释无法解决。当您单击UIButton时,@ IBAction pressPlay函数启动,这将导致地图上的滑块开始移动。滑块的最大值为0,最小值为-31,初始值为0,仅当拇指位于适当位置时它才开始移动! =从0开始,每1秒移动一次。这样可以正确移动滑块。

@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
        { //mette in play
            control = false
            playButton.setImage(pause,for: .normal)
            //removeSeismometers = true
            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))"
                        appo += 1
                        for i in mapEqAnnotation{
                            let str: String = i.eq.eventTime
                            let index = str.index(str.endIndex,offsetBy: -9)
                            let mySubstring = str[..<index]
                            nuovaData = calendario.date(byAdding: .day,value: Int(sliderTime.value),to:dataCorrente)!
                            let format = DateFormatter()
                            format.dateFormat = "yyyy-MM-dd"
                            let dataCntr = "\(format.string(from: nuovaData))"
                            if mySubstring == dataCntr{
                                printQuake(quake: i)
                            }else{
                                removeQuake(quake:i)
                            }
                        }
                        //printQuake(sliderValue: appo)
                    }else if cnt == 0{
                        //removeSeismometers = false
                        playButton.setImage(play,for: .normal)
                        timer!.invalidate()
                    }
                }
            }
        }else if control == false && Int(sliderTime.value) < 0 {
            playButton.setImage(play,for: .normal)
            control = true
            timer!.invalidate()
        }
    }

我的问题是,单击UIButton时,滑块必须每秒移动一次,并且必须在地图上添加注释,并在再次移动滑块后立即将其删除。 一切正常,除了当滚动条滚动时,上一个动作的注释不会消失,而是保留在地图上

    func printQuake(quake: MapEarthquakeAnnotation){
        let q = MapEarthquakeAnnotation(eq:quake.eq)
        mapView.addAnnotation(q)
    }

    func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView?
    {
        if annotation is MapEarthquakeAnnotation{
            annotazioni.append(annotation)
            let EQAnnotation = annotation as! MapEarthquakeAnnotation
            var view: MKPinAnnotationView
            view = MKPinAnnotationView(annotation: annotation,reuseIdentifier: EQAnnotation.identifier)
            view.canShowCallout = true
            view.pinTintColor = UIColor.brown
            return view
            
        }else if (annotation is MapSeismometerAnnotation) {
            if let annotation = annotation as? MapSeismometerAnnotation
            {
                var view: MKPinAnnotationView
                view = MKPinAnnotationView(annotation: annotation,reuseIdentifier: annotation.identifier)
                view.canShowCallout = true
                view.pinTintColor = UIColor.green
                view.image = UIImage(named: "pin-verde")
                return view
            }
            return nil
        }
        return nil
    }

能给我一些建议吗?

解决方法

removeQuake中查看您使用的代码会很有帮助,但是在快速查看代码之后,很可能是代码

func printQuake(quake: MapEarthquakeAnnotation){
    let q = MapEarthquakeAnnotation(eq:quake.eq)
    mapView.addAnnotation(q)
}

在这里,每次调用此方法时都会创建一个新的注释。而且此注释不会保留在任何地方。因此,当您致电removeQuake(quake:i)时,不能指望i是使用printQuake添加的任何注释。

我不确定为什么要创建该代码,但是您可能要做的就是将此方法更改为

func printQuake(quake: MapEarthquakeAnnotation){
    mapView.addAnnotation(quake)
}

通常,您的代码有点难以阅读。您应该研究使用Swift的更现代的方法,并且应该尝试拆分代码的各个部分,以便于阅读和维护。非英语语言也不是很有帮助。

我试图拆除并重建您的代码。并非所有内容都存在,并且我不确定它是否可以满足您的要求。但是仍然请检查一下。也许它将帮助您解决问题。

import UIKit
import MapKit

class ViewController: UIViewController {
    
    @IBOutlet private var mapView: MKMapView!
    @IBOutlet private var sliderTime: UISlider!
    @IBOutlet private var playButton: UIButton!
    @IBOutlet private var labelTime: UILabel!

    private var timer: Timer?
    private var earthquakeAnnotations: [MapEarthquakeAnnotation] = []
    
    private var dayOffset: Int = -30 {
        didSet {
            refresh()
        }
    }
    
    private var isPlaying: Bool = false {
        didSet {
            playButton.setImage(isPlaying ? UIImage(named: "play") : UIImage(named: "pause"),for: .normal)
        }
    }
    
    private func refresh() {
        let beginningOfToday: Date = Calendar.autoupdatingCurrent.date(from: Calendar.autoupdatingCurrent.dateComponents([.year,.month,.day],from: Date()))!
        let presentedDay = Calendar.autoupdatingCurrent.date(byAdding: .day,value: dayOffset,to: beginningOfToday)!
        refreshSlider()
        refreshTimeLabel(date: presentedDay)
        refreshAnnotations(date: presentedDay)
    }
    
    private func refreshSlider() {
        sliderTime.value = Float(dayOffset)
    }
    
    private func refreshTimeLabel(date: Date) {
        labelTime.text = {
            let formatter = DateFormatter()
            formatter.dateStyle = .medium
            return formatter.string(from: date)
        }()
    }
    
    private func refreshAnnotations(date: Date) {
        earthquakeAnnotations.forEach { annotation in
            if annotation.eq.date == date {
                if !mapView.annotations.contains(where: { $0 === annotation }) {
                    mapView.addAnnotation(annotation)
                }
            } else {
                if mapView.annotations.contains(where: { $0 === annotation }) {
                    mapView.removeAnnotation(annotation)
                }
            }
        }
    }
    
    private func stopPlaying() {
        timer?.invalidate()
        timer = nil
        isPlaying = false
    }
    
    private func startPlaying() {
        if dayOffset < 0 {
            isPlaying = true
            timer?.invalidate() // Just in case
            timer = Timer.scheduledTimer(withTimeInterval: 1.0,repeats: true,block: { [weak self] timer in
                guard let self = self else {
                    timer.invalidate()
                    return
                }
                
                if self.dayOffset < 0 {
                    self.dayOffset += 1
                } else {
                    self.stopPlaying()
                }
            })
        } else {
            // Already at the end. Should restart?
        }
    }
    
    @IBAction func pressPausePlay(_ sender: Any) {
        if isPlaying {
            stopPlaying()
        } else {
            startPlaying()
        }
    }
    
}

// MARK: - MKMapViewDelegate

extension ViewController: MKMapViewDelegate {
    
    func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if let annotation = annotation as? MapEarthquakeAnnotation {
            let view: MKPinAnnotationView = MKPinAnnotationView(annotation: annotation,reuseIdentifier: annotation.identifier)
            view.canShowCallout = true
            view.pinTintColor = UIColor.brown
            return view
        } else if let annotation = annotation as? MapSeismometerAnnotation {
            let view: MKPinAnnotationView = MKPinAnnotationView(annotation: annotation,reuseIdentifier: annotation.identifier)
            view.canShowCallout = true
            view.pinTintColor = UIColor.green
            view.image = UIImage(named: "pin-verde")
            return view
        } else {
            return nil
        }
    }
    
}

// MARK: - MapEarthquakeAnnotation

private extension ViewController {
    
    class MapEarthquakeAnnotation: NSObject,MKAnnotation {
        var identifier: String { "MapEarthquakeAnnotationID" }
        
        let coordinate: CLLocationCoordinate2D
        let eq: Earthquake
        
        init(earthquake: Earthquake,coordinate: CLLocationCoordinate2D) { self.eq = earthquake; self.coordinate = coordinate }
    }
    
}

// MARK: - MapSeismometerAnnotation

private extension ViewController {
    
    class MapSeismometerAnnotation: NSObject,MKAnnotation {
        var identifier: String { "MapSeismometerAnnotationID" }
        
        let coordinate: CLLocationCoordinate2D
        
        init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate }
    }
    
}

// MARK: - Earthquake

private extension ViewController {
    
    struct Earthquake {
        let eventTime: String
        
        var date: Date {
            let index = eventTime.index(eventTime.endIndex,offsetBy: -9)
            let format = DateFormatter()
            format.dateFormat = "yyyy-MM-dd"
            return format.date(from: String(eventTime[..<index])) ?? Date()
        }
    }
    
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res