如何解决呈现自定义批注时,MKMapView冻结
大约有 1500个自定义注释,其中包含值和图像。
我了解到,这种自定义功能需要实时渲染,价格很高,但是用户界面在注解期间(用户时,UI处于冻结状态(有时)移动地图,每个注释都会花费一些时间进行渲染,并且其放大得更多,出现更多的注释,并且UI冻结的时间也就更长。
在android的同一个应用程序中,我设法通过将所有注释聚集到视线之外,仅在可见时才渲染它们,而不会冻结地图。
渲染必须在后台在主线程之外进行。
也欢迎其他建议。
某些代码:viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
mapView.register(CustomPinAnnotationView.self,forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
// mapView.register(CustomPinAnnotationView.self,forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)
... configureDatabase()
... loadMapMap()
... loadAnnotations()
}
更多代码:viewfor批注
func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation.isMember(of: MKUserLocation.self) { return nil }
if annotation is MKClusterAnnotation { return nil }
guard let customAnnotation = annotation as? CustomPin else { return nil }
... GET ANNOTATION INFO ...
let reusePin = preco+stared+fechado+excluido+publico+particular
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reusePin) as? CustomPinAnnotationView
if pinView == nil { pinView = CustomPinAnnotationView(annotation: annotation,reuseIdentifier: reusePin) }
else { return pinView }
... RENDER CUSTOM ANNOTATION IMAGE ...
UIGraphicsEndImageContext()
pinView?.canShowCallout = true
pinView?.centerOffset = CGPoint(x: size.width / 5,y: -size.height / 5)
print("=",terminator:"")
return pinView
}
CustomPinAnnotationView.swift
import Foundation
import UIKit
import MapKit
class CustomPinAnnotationView: MKAnnotationView {
private var observerContext = 0
override init(annotation: MKAnnotation?,reuseIdentifier: String?) {
super.init(annotation: annotation,reuseIdentifier: reuseIdentifier)
clusteringIdentifier = "cluster"
collisionMode = .circle
centerOffset = CGPoint(x: 0,y: -10) // Offset center point to animate better with marker annotations
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var annotation: MKAnnotation? {
willSet {
removeObserverIfAny()
}
didSet {
if let annotation = annotation as? CustomPin {
annotation.addObserver(self,forKeyPath: #keyPath(CustomPin.subtitle),context: &observerContext)
}
}
}
deinit {
removeObserverIfAny()
}
private func removeObserverIfAny() {
if let oldAnnotation = annotation as? CustomPin {
oldAnnotation.removeObserver(self,forKeyPath: #keyPath(CustomPin.subtitle))
}
}
override func observeValue(forKeyPath keyPath: String?,of object: Any?,change: [NSKeyValueChangeKey : Any]?,context: UnsafeMutableRawPointer?) {
guard context == &observerContext else {
super.observeValue(forKeyPath: keyPath,of: object,change: change,context: context)
return
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。