Iphone 是否用注释中的文本标签替换图标pin?
是否可以用动态文本标签替换批注的pin图标 可能使用css,或者动态创建图像 例如,标签是在谷歌地图API上用CSS和JavaScript完成的。是的,这是可能的 在iOS MapKit中,您需要实现Iphone 是否用注释中的文本标签替换图标pin?,iphone,ios,mapkit,Iphone,Ios,Mapkit,是否可以用动态文本标签替换批注的pin图标 可能使用css,或者动态创建图像 例如,标签是在谷歌地图API上用CSS和JavaScript完成的。是的,这是可能的 在iOS MapKit中,您需要实现viewForAnnotationdelegate方法,并返回添加了UILabel的MKAnnotationView 例如: -(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnot
viewForAnnotation
delegate方法,并返回添加了UILabel的MKAnnotationView
例如:
-(MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id<MKAnnotation>)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;
}
-(MKAnnotationView*)映射视图:(MKMapView*)映射视图
viewForAnnotation:(id)注释
{
if([annotation isKindOfClass:[MKUserLocation类]])
返回零;
静态NSString*reuseId=@“reuseId”;
MKAnnotationView*av=[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
如果(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];
//如果您点击标签,下面的标注仍然有效。。。
av.canShowCallout=是;
av.frame=lbl.frame;
}
其他的
{
av.annotation=注释;
}
UILabel*lbl=(UILabel*)[av viewWithTag:42];
lbl.text=annotation.title;
返回av;
}
确保地图视图的delegate
属性已设置,否则将不会调用此委托方法,而您将获得默认的红色PIN。这里是上面的注释中提到的委托方法的Swift 3变体。确保您的类符合MKMapViewDelegate,并且在viewDidLoad()中将mapView的委托设置为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
}