17
A
回答
30
是的,這是可能的。
在iOS MapKit中,您需要實施viewForAnnotation
委託方法,並返回MKAnnotationView
並添加UILabel
。
例如:
-(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;
}
確保地圖視圖的delegate
屬性的設置,否則此委託方法將不會被調用,你會得到默認的紅色圖釘來代替。
2
下面是Anna上面評論中提到的代理方法的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
}
你好,試着再詳細一點。可以嘗試一些代碼。 – 2012-03-22 13:13:35