当用户触摸地图时,我在添加注释方面遇到了一些问题。
我正在使用UIGestureRecognizer
来检测用户的触摸。
当检测到长按时,我正在调用此功能:
- (void)handleLongPressGesture:(UIGestureRecognizer*)gestureRecognizer{
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) return;
NSLog(@"long press");
CGPoint touchPoint = [gestureRecognizer locationInView:mapView];
CLLocationCoordinate2D touchMapCoordinate =
[mapView convertPoint:touchPoint toCoordinateFromView:mapView];
RdvAnnotation *rdvAnnotation = [[RdvAnnotation alloc] init];
[rdvAnnotation initWithCoordinate:touchMapCoordinate];
[mapView removeAnnotations:mapView.annotations];
[mapView addAnnotation:rdvAnnotation];
[rdvAnnotation release]; }
我可以在控制台中看到NSLog,并使用良好的坐标初始化rdvAnnotation
。
我不明白为什么我在地图上看不到我的注释。
这是我的- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
方法:
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
if ([annotation isKindOfClass:[RdvAnnotation class]])
{
static NSString* RdvAnnotationIdentifier = @"rdvAnnotationIdentifier";
MKPinAnnotationView* pinView = (MKPinAnnotationView *)
[mapView dequeueReusableAnnotationViewWithIdentifier:RdvAnnotationIdentifier];
if (!pinView)
{
MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:RdvAnnotationIdentifier] autorelease];
customPinView.pinColor = MKPinAnnotationColorPurple;
customPinView.animatesDrop = YES;
customPinView.canShowCallout = YES;
return customPinView;
}
else
{
pinView.annotation = annotation;
}
return pinView;
}
return nil;}
我的viewDidLoad
方法:
- (void)viewDidLoad {
[super viewDidLoad];
mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
[mapView setShowsUserLocation:TRUE];
[mapView setMapType:MKMapTypeStandard];
[mapView setDelegate:self];
CLLocationManager *locationManager=[[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager startUpdatingLocation];
self.navigationItem.title = @"Rendez-vous" ;
}
答案 0 :(得分:0)
我刚注意到一些看起来很奇怪的东西:
RdvAnnotation *rdvAnnotation = [[RdvAnnotation alloc] init];
[rdvAnnotation initWithCoordinate:touchMapCoordinate];
您在注释对象上调用了两次init。你应该这样做:
RdvAnnotation *rdvAnnotation = [[RdvAnnotation alloc] initWithCoordinate:touchMapCoordinate]];
编辑: 如果您的init方法中的代码不想丢失,请保留init并更改坐标属性的值:
RdvAnnotation *rdvAnnotation = [[RdvAnnotation alloc] init];
rdvAnnotation.coordinate = touchMapCoordinate;
答案 1 :(得分:0)
在viewDidLoad
中,您正在创建一个新的地图视图对象。
首先,这个新的地图视图对象不会作为子视图添加到self.view
,因此它存在于内存中但不可见。
其次,您可能已经在Interface Builder中的视图中放置了一个地图视图对象,因此您无需创建新对象。
所以可能发生的事情是,当你添加注释时,它会被添加到内存中的地图视图对象中,但不会被添加到可见的那个(在IB中创建的那个)。
不是在viewDidLoad
中创建新的地图视图,而是将mapView
IBOutlet连接到Interface Builder中的地图视图。