I’ve tried adding a MKMapView into my new app. I created a custom MKAnnotationView -> so I can change the pin’s image. Everything works until I try to drag the pin. No matter what I do, it just wont. There is only one more thing left to say; the MapView is a subview of a big tableView cell. But the panning and zooming work properly, so I don’t suppose it has to do with that…
Here is my code:
MKAnnotation
@interface MyAnnotation : NSObject <MKAnnotation> {
}
//MKAnnotation
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@end
@implementation MyAnnotation
@synthesize coordinate;
@end
MKAnnotationView
@interface MyAnnotationView : MKAnnotationView {
}
@end
@implementation MyAnnotationView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, 38, 43)];
if (self) {
// Initialization code
UIImage* theImage = [UIImage imageNamed:@"partyPin.png"];
if (!theImage)
return nil;
self.image = theImage;
}
return self;
}
@end
The view the MapView is in – delegate methods – not including the part where I init the MKAnnotation and “addAnnotation”
- (MKAnnotationView *)mapView:(MKMapView *)lmapView viewForAnnotation:(id <MKAnnotation>)annotation {
MyAnnotationView *myAnnotationView = (myAnnotationView *)[lmapView dequeueReusableAnnotationViewWithIdentifier:@"myView"];
if(myAnnotationView == nil) {
myAnnotationView = [[MyAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myView"];
}
myAnnotationView.draggable = YES;
myAnnotationView.annotation = annotation;
return myAnnotationView;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState
{
if (newState == MKAnnotationViewDragStateEnding)
{
CLLocationCoordinate2D droppedAt = annotationView.annotation.coordinate;
NSLog(@"dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);
}
}
Does anyone see what I missed?
Thanks very much in advance!
For an annotation to be draggable, it must implement a
setCoordinatemethod. Just setting the view’sdraggableproperty toYESis not enough.Your annotation class has defined
coordinateasreadonly.Instead, define it as
readwriteorassignand remove thecoordinatemethod (as well as thelatitudeandlongitudeivars and properties since you’ll be able to set the coordinate directly).Also add an
@synthesize coordinateso you don’t have to write the getter/setter manually.