如何解决Mapview Swift的自定义注释
我查看了相关信息,但仍未收到自定义图钉...。
import UIKit
import MapKit
class CustomPointAnnotation: MKPointAnnotation {
var pinCustomImageName: UIImage!
}
视图控制器:
我想返回当前位置,直到选择了一个按钮以放置图钉
func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {
//current Location
if !(annotation is CustomPointAnnotation) {
return nil
}
let reuseIdentifier = "pin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation,reuseIdentifier: reuseIdentifier)
annotationView!.canShowCallout = true
} else {
annotationView!.annotation = annotation
}
if let annotationView = annotationView {
annotationView.image = UIImage(named: "Skyscraper")
annotationView.canShowCallout = true
}
return annotationView
}
func addPin() {
pointAnnotation = CustomPointAnnotation()
pointAnnotation.pinCustomImageName = UIImage(named: "Skyscraper")
pointAnnotation.coordinate = currentLocation.coordinate
pointAnnotation.title = "First Building"
pointAnnotation.subtitle = "Latitude: \(currentLocation.coordinate.latitude),\
(currentLocation.coordinate.longitude)"
mapView.addAnnotation(pointAnnotation)
}
解决方法
代码没有严重错误。但是可能有几件事会引起问题,包括:
-
您是否为地图视图设置了
delegate
(在IB中还是通过编程方式)?如果没有,您的mapView(_:viewFor:)
将永远不会被调用。添加断点或调试print
语句以确认。 -
您是否已确认
UIImage(named: "Skyscraper")
正在成功检索图像?确保这没有返回nil
。
请注意,如果只有iOS 11及更高版本,则可以稍微简化一下此代码。从iOS 11开始,在这样的简单情况下,我们不再需要mapView(_:viewFor:)
。我建议将批注视图配置代码放在批注视图子类(所属的子类)中,并避免使用viewFor
实现使我们的视图控制器混乱。
因此,当您遇到当前问题时,建议的流程是:
-
为注释和注释视图定义类:
class CustomAnnotation: MKPointAnnotation { var pinCustomImage: UIImage! }
和
class CustomAnnotationView: MKAnnotationView { override init(annotation: MKAnnotation?,reuseIdentifier: String?) { super.init(annotation: annotation,reuseIdentifier: reuseIdentifier) canShowCallout = true update(for: annotation) } override var annotation: MKAnnotation? { didSet { update(for: annotation) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func update(for annotation: MKAnnotation?) { image = (annotation as? CustomAnnotation)?.pinCustomImage } }
-
在
viewDidLoad
中注册此注释视图类:mapView.register(CustomAnnotationView.self,forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
-
删除
mapView(_:viewFor:)
实现。
现在,当您在地图的注释列表中添加CustomAnnotation
时,它将正确显示。
但是我建议您先解决当前的问题。在解决这些更基本的问题之前,没有必要完善您的实施。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。