カスタム AnnotationViews を使用するアプリケーションに取り組んでいます。カスタム画像とラベル付きの背景があります。背景とラベルは、annotationView のサブビューです。
if ([annotation isKindOfClass:[VehicleAnnotation class]]) {
VehicleAnnotation *vehicleAnnotation = annotation;
MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:driverAnnotationIdentifier];
if(!pinView)
{
pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:driverAnnotationIdentifier];
}
pinView.annotation = annotation;
pinView.canShowCallout = NO;
pinView.image = [ImageHelper imageForStatus:vehicleAnnotation.vehicle.driver.driverStatus];
// Add a label with the name of the driver
CGRect pinFrame = pinView.frame;
UILabel *label = [[UILabel alloc] init];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextColor:[UIColor whiteColor]];
[label setNumberOfLines:2];
[label setLineBreakMode:NSLineBreakByWordWrapping];
[label setFont:[UIFont systemFontOfSize:12]];
label.text = vehicleAnnotation.vehicle.driver.description;
CGSize maximumSize = CGSizeMake(100, 50);
CGSize myStringSize = [label.text sizeWithFont:label.font
constrainedToSize:maximumSize
lineBreakMode:label.lineBreakMode];
CGRect labelFrame = CGRectMake(pinFrame.origin.x, pinFrame.origin.y + pinFrame.size.height * 2 + 2, myStringSize.width, myStringSize.height);
[label setFrame:labelFrame];
// Add a background to the label.
CGFloat offset = 5;
CGRect backgroundFrame = CGRectMake(labelFrame.origin.x - offset, labelFrame.origin.y - offset , labelFrame.size.width + 2 * offset, labelFrame.size.height + 2 * offset);
UIView *backgroundView = [[UIView alloc] initWithFrame:backgroundFrame];
backgroundView.layer.cornerRadius = 5;
backgroundView.layer.masksToBounds = YES;
[backgroundView setBackgroundColor:[UIColor darkGrayColor]];
[backgroundView setAlpha:0.8];
[pinView addSubview:backgroundView];
[label setUserInteractionEnabled:YES];
[label setMultipleTouchEnabled:YES];
[pinView addSubview:label];
return pinView;
}
このコードは、新しい位置が受信されるたびに実行されます。問題は、古いラベルと古い背景がまだ残っていることです。だから私はこのコードを入れたと思った:
MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:driverAnnotationIdentifier];
if(!pinView)
{
pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:driverAnnotationIdentifier];
}
for(UIView *view in [pinView subviews])
{
[view removeFromSuperview];
}
pinView.annotation = annotation;
ただし、ラベルや背景は表示されません。背景とラベルを適切な方法で交換または削除するのを手伝ってくれる人はいますか?
ありがとうございました!