我正在尝试为注释添加标题,但是在点击地图上的相关点时我看不到它。
要添加它我使用:
for( NSDictionary *dic in [GlobalData sharedGlobals].currentBusinessList)
{
NSString *title=[dic objectForKey:@"name"];
double latitude=[[dic objectForKey:@"latitude"] doubleValue];
double longitude=[[dic objectForKey:@"longitude"] doubleValue];
CLLocationCoordinate2D location = CLLocationCoordinate2DMake(latitude,longitude);
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
MKPinAnnotationView *pointV = [[MKPinAnnotationView alloc] initWithAnnotation:point reuseIdentifier:nil];
[point setCoordinate:location];
point.title = title;
[self.mapView addAnnotation:pointV.annotation];
MKCoordinateRegion region = self.mapView.region;
region.center = location;
region.span.longitudeDelta /= 5.0;
region.span.latitudeDelta /= 5.0;
[self.mapView setRegion:region];
}
现在这很有效。但你不能在这里设置颜色 - 它不起作用,但只有在这里添加回调来设置颜色:
- (MKAnnotationView *) mapView:(MKMapView *)mapView
viewForAnnotation:(id <MKAnnotation>) annotation
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"pin"];
//point.title=@"ran"; also not working
annView.pinColor = MKPinAnnotationColorPurple;
annView.animatesDrop=YES;
return annView;
}
但似乎添加这个会阻止标题显示。
似乎我只能获得其中一个,标题或颜色。 如果我在这里取出第二种方法,我可以看到标题,但是,在第一种方法中设置颜色是行不通的。
用标题和颜色添加几个注释的正确方法是什么?
答案 0 :(得分:1)
不,您可以更改颜色并显示标题。到目前为止,您的代码看起来不错,但请将此行添加到(MKAnnotationView *) mapView:(MKMapView *)mapView
viewForAnnotation:(id <MKAnnotation>) annotation
pinAnno.canShowCallout = YES;
答案 1 :(得分:1)
您需要创建一个符合NSAnnotation协议的类并使用它而不是使用MKPointAnnotation
创建您自己的类,例如MyAnnotation
MyAnnotation .h文件
#import <MapKit/MapKit.h>
@interface MyAnnotation : NSObject <MKAnnotation>
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, readonly, copy) NSString *title;
@property (nonatomic, readonly, copy) NSString *subtitle;
- (instancetype)initWithTitle:(NSString *)title andSubTitle:(NSString *)subtitle atCoordinate:(CLLocationCoordinate2D)coordinate;
@end
MyAnnotation .m文件
#import "MyAnnotation.h"
@implementation MyAnnotation
- (instancetype)initWithTitle:(NSString *)title andSubTitle:(NSString *)subtitle atCoordinate:(CLLocationCoordinate2D)coordinate
{
self = [super init];
if (self) {
_title = title;
_subtitle = subtitle;
_coordinate = coordinate;
}
return self;
}
@end
然后使用您的类创建注释
代替此代码
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
MKPinAnnotationView *pointV = [[MKPinAnnotationView alloc] initWithAnnotation:point reuseIdentifier:nil];
[point setCoordinate:location];
point.title = title;
[self.mapView addAnnotation:pointV.annotation];
添加此代码
MyAnnotation *annotation = [[MyAnnotation alloc] initWithTitle:title andSubTitle:nil atCoordinate:location];
[self.mapView addAnnotation:annotation];