问题
I am building an iOS app and need to be able to place a pin where the user currently is! For some reason I have been having an awful time getting it to work! I tried the following code but was faced with an error.
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation == mapView.userLocation)
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
[annView release];
}
}
The error was: Control May Reach End of non-void function.
Thank you so much for the help! ' Appreciate it!
回答1:
The following code works fine in the Xcode iPhone simulator:
#import "ViewController.h"
@import MapKit;
@interface ViewController () <MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.mapView setDelegate:self];
[self.mapView setShowsUserLocation:YES];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
// zoom to region containing the user location
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
// add the annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate;
point.title = @"The Location";
point.subtitle = @"Sub-title";
[self.mapView addAnnotation:point];
}
@end
回答2:
When a method has a return type then something must be returned in all conditions, you are only returning something in the if branch, not otherwise. The compiler requires you to also return something when the if statement evaluates to false - that is the reason why you are getting the compilation error.
Incidentally the line
[annView release];
can never get executed because you are returning before then. But is there any reason why you are calling this? i.e. attempting to use non ARC code? Have you copied this line from somewhere (which is old code)
来源:https://stackoverflow.com/questions/23922625/drop-pin-on-current-location