如何解决如何将自定义XIB用于MKAnnotationView?
我想使用自定义的XIB代替MKAnnotation View,但是我找不到任何可以帮助我的在线资源。 明确地说,我不需要标注,我不需要图像代替销钉,我希望将其完全替换为xib。 供参考,我希望我的别针看起来像这样-
https://i.stack.imgur.com/gbdFI.png
这将是图钉设计,中间的图像对于所有用户都将更改。 我从未使用过MKMapView,在观看了一些有关MKMapView的教程之后,我只是在地图上显示了MKPinAnnotationView。 有人可以指导我如何实现这一目标
编辑: 使用Alexander nikolaychuk的链接,我能够使用XIB创建MKPinAnnotationViews。
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 = "CustomPinAnnotation"
let nibName = "CustomPinAnnotation"
let viewFromNib = Bundle.main.loadNibNamed(nibName,owner: self,options: nil)?.first as! CustomPinAnnotation
var annotationView: CustomPinAnnotation?
// if there is a view to be dequeued,use it for the annotation
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) as? CustomPinAnnotation {
if dequeuedAnnotationView.subviews.isEmpty {
dequeuedAnnotationView.addSubview(viewFromNib)
}
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
} else {
// if no views to dequeue,create an Annotation View
let av = CustomPinAnnotation(annotation: annotation,reuseIdentifier: annotationIdentifier)
av.addSubview(viewFromNib)
annotationView = av // extend scope to be able to return at the end of the func
}
// after we manage to create or dequeue the av,configure it
if let annotationView = annotationView {
annotationView.canShowCallout = true // callout bubble
annotationView.rightCalloutAccessoryView = UIButton(type: .detaildisclosure)
annotationView.frame = CGRect(x: 0,y: 0,width: 40,height: 40)
let customView = annotationView.subviews.first as! CustomPinAnnotation
customView.frame = annotationView.frame
customView.profilePicImageView.image = UIImage(named: "dummy4")
}
return annotationView
}
}
现在,我的应用程序中还有2个问题
-
我想以阵列模式显示在地图上的所有数据。如何使用模态中的个人资料图片网址并将其显示在注释视图中的imageView上?由于viewFor批注不会迭代且没有任何索引值,因此在此处传递模态对我来说是一个挑战。
-
即使我的xIB看起来像这样: https://i.stack.imgur.com/Wg4ZU.png
在MapView上看起来像这样:https://i.stack.imgur.com/e7CAr.jpg
解决方法
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: MKPinAnnotationView?
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "AnnotationIdentifier") as? MKPinAnnotationView {
//Here you can setup
annotationView = dequeuedAnnotationView
annotationView?.annotation = annotation
}
}
您不需要自行初始化。它使用自定义的CollectionViewCells。尝试使用此示例。 (这是委托函数FYI)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。