我希望拥有一个自定义的MKAnnotationView。我已经在IB中创建了一个xib文件,并将其类设置为MyAnnotationView。
class MyAnnotationView: MKAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var busIcon: UIImageView!
}
这是xib的样子 - 它有一个textLabel和一个busIcon链接: 我正在使用
viewFor annotation
委托方法为所有注释创建视图:func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// Don't want to show a custom image if the annotation is the user's location.
if (annotation is MKUserLocation) {
return nil
} else {
let annotationIdentifier = "AnnotationIdentifier"
var annotationView: MyAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "AnnotationIdentifier") as? MyAnnotationView {
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
} else {
// if no views to dequeue, create an Annotation View
let av = MyAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
av.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
annotationView = av
}
if let annotationView = annotationView {
annotationView.canShowCallout = true // callout bubble
annotationView.image = UIImage(named: "Delivery")
annotationView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
}
return annotationView
}
}
annotationView.image = UIImage(named: "Delivery")
&
AnnotationView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
这些代码只是为了检查代码是否正常工作,并在地图上显示样本视图,因为它们使用从 MKAnnotationView 继承的标准属性。
我不知道如何使 viewFor annotation
方法使用我创建的 XIB。有人可以帮助我吗?我搜索了解决方法,但只找到了一些与 Obj C 相关的内容。
谢谢!