如何在iOS中使用Map Kit制作自定义注释?

时间:2014-05-09 14:03:49

标签: ios mapkit

我想制作一个包含3个图像和5个按钮的MapKit注释,就像点击注释图钉一样,弹出信息框会出现标题和副标题。我可以使用setRightCalloutAccessoryView左右放置图像和按钮,但如何制作完全自定义的视图?

1 个答案:

答案 0 :(得分:1)

有一个关于此的教程,可在以下位置找到:
http://www.codigator.com/tutorials/advanced-mapkit-tutorial-for-ios-custom-callout/ 我将在下面描述一个概述。

如果包含mapView的viewcontroller符合MKMapViewDelegate协议,则可以响应didSelectAnnotationView方法。这允许我们使用我们需要的任何控件创建自定义视图。此示例中未显示自定义视图的位置:

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    // note that we don't do this if the selected annotation is for the user location
    if(![view.annotation isKindOfClass:[MKUserLocation class]]) {

        UIView * myCustomView = [self createMyCustomView];
       [view addSubview:myCustomView];

        // you can also load a view from a xib file.  
        // If there are going to be a lot of annotations, I'd probably load a xib
        // to a local view property during the parent view controller's viewDidLoad,
        // and simply refresh the contents of that view whenever this is called.
    }
}

// Build a view hierarchy programmatically.
- (UIView *) createMyCustomView {

    UIView * myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    UIImageView * myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [myImage setImage:[UIImage imageNamed:@"some_image"]];
    [myView addSubview:myImage];

    UIButton * thisButton = [[UIButton alloc] initWithFrame:CGRectMake(50,50, 50, 10)];
    [thisButton.titleLabel setText:@"My Button"];
    [thisButton addTarget:self action:@selector(handleMyButton:) forControlEvents:UIControlEventTouchUpInside];
    [myView addSubview:thisButton];

    // etc.

    return myView;

}

因此,您还应该响应didDeselectAnnotationView协议:

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    for (UIView *subview in view.subviews ){
        [subview removeFromSuperview];
    }
}