您的位置:首页 > 其它

104 自定义大头针

2015-11-09 10:36 316 查看
1.每次添加一个大头针系统会调用mapview的以下代理方法:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
//如果返回nil,就相当于没有任何处理,系统会按照原有的方式进行显示
一开始定位到了之后会显示一个蓝色发光的大头针,这个大头针模型是系统的
if (![annotation isKindOfClass:[HMAnnotation class]]) {
//如果是系统的不做处理
return nil;
}
}


2.默认情况下MKAnnotationView是无法显示的(设置image才能显示), 如果想自定义大头针可以使用MKAnnotationView的子类MKPinAnnotationView

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
static NSString *identifier = @"anno";
MKPinAnnotationView *annoView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annoView == nil) {
annoView = [[MKPinAnnotationView alloc] initWithAnnotation:nil reuseIdentifier:identifier];
// 设置大头针的颜色
annoView.pinColor = MKPinAnnotationColorPurple;

// 设置大头针从天而降
annoView.animatesDrop = YES;

// 设置大头针标题是否显示,默认不显示
annoView.canShowCallout = YES;

// 设置大头针标题显示的偏移位
annoView.calloutOffset = CGPointMake(-50, 0);

// 设置大头针左边的辅助视图
annoView.leftCalloutAccessoryView = [[UISwitch alloc] init];
// 设置大头针右边的辅助视图
annoView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
}
// 注意: 如果你是使用的MKPinAnnotationView创建的自定义大头针, 那么设置图片无效,
//因为系统内部会做一些操作, 覆盖掉我们自己的设置,这个时候只能使用父类MKAnnotationView

// 3.给大头针View设置数据
annoView.annotation = annotation;

// 4.返回大头针View
return annoView;
}


3.MKAnnotationView设置自定义的图片:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
static NSString *identifier = @"anno";
MKAnnotationView *annoView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annoView == nil) {
annoView = [[MKAnnotationView alloc] initWithAnnotation:nil reuseIdentifier:identifier];

// 设置大头针标题是否显示,默认不显示
annoView.canShowCallout = YES;

// 设置大头针标题显示的偏移位
annoView.calloutOffset = CGPointMake(-50, 0);

// 设置大头针左边的辅助视图
annoView.leftCalloutAccessoryView = [[UISwitch alloc] init];
// 设置大头针右边的辅助视图
annoView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
}
// 注意: 如果你是使用的MKPinAnnotationView创建的自定义大头针, 那么设置图片无效,
//因为系统内部会做一些操作, 覆盖掉我们自己的设置,这个时候只能使用父类MKAnnotationView
annoView.image = [UIImage imageNamed:@"123"];
// 3.给大头针View设置数据
annoView.annotation = annotation;

// 4.返回大头针View
return annoView;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: