我查看了相关信息,但仍未收到自定义图钉...。
自定义注释->包括设置我的图片
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)
}
答案 0 :(得分:0)
代码没有严重错误。但是可能有几件事会引起问题,包括:
您是否为地图视图设置了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
时,它将正确显示。
但是我建议您先解决当前的问题。在解决这些更基本的问题之前,没有必要完善您的实施。