2012-10-14 58 views
2

我已经在.H添加UIViewController<MKMapViewDelegate>和已经添加MKAnnotation viewForAnnotation从来没有所谓的

-(void) viewDidLoad { 
    self.mapView.delegate = self; 
} 

但该方法viewForAnnotation从来没有所谓的

MapViewController.h

#import <UIKit/UIKit.h> 
    #import <MapKit/MapKit.h> 

    @interface Tela1ViewController : UIViewController<MKMapViewDelegate> { 
     IBOutlet MKMapView *mapView; 
    } 

    @property (nonatomic, retain) MKMapView *mapView; 
    @end 

MapViewController.m

-(void) viewDidLoad { 
     self.mapView.delegate = self; 
    } 

    - (void)viewDidAppear:(BOOL)animated 
    { 
     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication shared 

     mapView = [[MKMapView alloc] initWithFrame:self.view.bounds]; 
     mapView.mapType = MKMapTypeSatellite; 

     CLLocationCoordinate2D coord = {latitude: appDelegate.latitude, longitude: appDelegate.longitude}; 
     MKCoordinateSpan span = {latitudeDelta:0.2, longitudeDelta: 0.2}; 
     MKCoordinateRegion region = {coord, span}; 

     [mapView setRegion:region]; 

     PlaceMark *addAnnotation = [[PlaceMark alloc] initWithCoordinate:coord]; 
     [mapView addAnnotation:addAnnotation]; 
     [self.view addSubview:mapView]; 
    } 

    - (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation 
    { 
     NSLog(@"test"); 
    } 
+0

验证您的mapView插座在InterfaceBuilder中正确连接。如果是,发布实际的@interface行,并发布你的mapView:viewForAnnotation:方法。 –

+0

是的,已连接 – Developer2012

+0

顺便说一句,你必须在'viewDidAppear:'方法的某个时刻调用'[super viewDidAppear:animated'。 – robertvojta

回答

3

好吧,两件事情在你的代码修复...的MKMapView的

代表

nil。为什么?因为在viewDidLoad方法中设置MKMapView的代理人。但是当你看到viewDidAppear:时,你正在分配新的MKMapView,并且你没有在那里设置委托。并且因为viewDidLoadviewDidAppear:之前被调用,因此委托仅仅是nil =未设置。

调用超级

当你重写一些方法,阅读文档。因为您可以在viewDidAppear:文档中找到此示例,例如:

您可以重写此方法以执行与呈现视图相关的其他任务。如果您重写此方法,则必须在实现中的某个时刻调用super。

的MKMapView & IBOutlet中

而且也想不明白,为什么你有MKMapView作为IBOutlet,然后你分配新MKMapView并将其添加为子视图。另外,如果您的IBOutlet真的连接到您的XIB中的MKMapView,则最终将有两个MKMapView s,因为旧的(来自XIB)未从超级视图中移除。

你明显搞砸了。去读更多关于UIKit,...

0

尝试用替换你的最后几行viewDidAppear方法如下:

CLLocationCoordinate2D coord = {.latitude = location.latitude, .longitude = location.longitude}; 
MKCoordinateSpan span = {.latitudeDelta = 0.2, .longitudeDelta = 0.2}; 
MKCoordinateRegion region = {coord, span}; 

[mapView setRegion:region]; 

MapAnnotation *addAnnotation = [[MapAnnotation alloc] initWithCoordinate:coord]; 
[mapView addAnnotation:addAnnotation]; 
[self.view addSubview:mapView]; 
相关问题