[plain]
<span style="font-size:16px;">MKAnnotationView* aView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MyCustomAnnotation"] autorelease]; aView.image = [UIImage imageNamed:@"myimage.png"]; aView.centerOffset = CGPointMake(10, -20); </span> 在代理的mapView:viewForAnnotation:方法中创建标准注释视图
[plain]
<span style="font-size:16px;">#import <UIKit/UIKit.h> #import <MapKit/MapKit.h> @interface MyCustomAnnotationView : MKAnnotationView { // Custom data members } // Custom properties and methods. @end </span>
[plain]
<span style="font-size:16px;">Listing 5-5 Initializing a custom annotation view - (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier]; if (self) { // Set the frame size to the appropriate values. CGRect myFrame = self.frame; myFrame.size.width = 40; myFrame.size.height = 40; self.frame = myFrame; // The opaque property is YES by default. Setting it to // NO allows map content to show through any unrendered // parts of your view. self.opaque = NO; } return self; } </span>6.在代理对象中创建注释视图
[plain]
<span style="font-family:Arial;color:#333333;"><span style="font-size:16px;">Listing 5-6 Creating annotation views - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { // If it's the user location, just return nil. if ([annotation isKindOfClass:[MKUserLocation class]]) return nil; // Handle any custom annotations. if ([annotation isKindOfClass:[MyCustomAnnotation class]]) { // Try to dequeue an existing pin view first. MKPinAnnotationView* pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"]; if (!pinView) { // If an existing pin view was not available, create one. pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotation"] autorelease]; pinView.pinColor = MKPinAnnotationColorRed; pinView.animatesDrop = YES; pinView.canShowCallout = YES; // Add a detail disclosure button to the callout. UIButton* rightButton = [UIButton buttonWithType: UIButtonTypeDetailDisclosure]; [rightButton addTarget:self action:@selector(myShowDetailsMethod:) forControlEvents:UIControlEventTouchUpInside]; pinView.rightCalloutAccessoryView = rightButton; } else pinView.annotation = annotation; return pinView; } return nil; } </span></span>当map view需要显示注释时候,会调用代理的mapView:viewForAnnotation:方法,如果你不实现此方法或者总是返回nil,map view会使用默认的注释视图,即pin annotation view。在你创建新的视图之前,检查是否已经存在此类视图dequeueReusableAnnotationViewWithIdentifier: ,类似于tableview的cell实现
7.管理地图的注释对象
为了避免注释视图的重叠,在方法mapView:regionWillChangeAnimated: andmapView:regionDidChangeAnimated: 中,根据需要来添加或者减少
8.让注释视图可拖动
在注释对象中,实现setCoordinate:方法来更新注释的坐标。 创建注释视图时,设置draggable属性为YES