在注释中用文本标签替换图标引脚?

是否可以用动态文本标签替换注释的图钉图标?

也许使用CSS,或动态创建图像?

例如,使用JavaScript在Google Maps API上使用CSS完成标签。

是的,这是可能的。

在iOS MapKit中,您需要实现viewForAnnotation委托方法并返回添加了UILabelMKAnnotationView

例如:

 -(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation { if ([annotation isKindOfClass:[MKUserLocation class]]) return nil; static NSString *reuseId = @"reuseid"; MKAnnotationView *av = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId]; if (av == nil) { av = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId] autorelease]; UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 30)] autorelease]; lbl.backgroundColor = [UIColor blackColor]; lbl.textColor = [UIColor whiteColor]; lbl.alpha = 0.5; lbl.tag = 42; [av addSubview:lbl]; //Following lets the callout still work if you tap on the label... av.canShowCallout = YES; av.frame = lbl.frame; } else { av.annotation = annotation; } UILabel *lbl = (UILabel *)[av viewWithTag:42]; lbl.text = annotation.title; return av; } 

确保设置了地图视图的delegate属性,否则将不会调用此委托方法,您将获得默认的红色引脚。

这是上面安娜评论中提到的委托方法的Swift 3变体。 确保您的类符合MKMapViewDelegate,并且mapView的委托在viewDidLoad()中设置为self。

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } let reuseId = "reuseid" var av = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) if av == nil { av = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 30)) lbl.backgroundColor = .black lbl.textColor = .white lbl.alpha = 0.5 lbl.tag = 42 av?.addSubview(lbl) av?.canShowCallout = true av?.frame = lbl.frame } else { av?.annotation = annotation } let lbl = av?.viewWithTag(42) as! UILabel lbl.text = annotation.title! return av } 
Interesting Posts