晚上好,我在使用当用户按下视图控制器上的栏按钮时加载 MapView 的应用程序时遇到问题。MapViewController 被加载,地图显示正确的注释(未显示在源代码中),但在第一次启动应用程序并打开 MapView 时,起始区域是错误的。当我按一次后退按钮并重新打开 MapView 时,开始区域很好。它只是第一次不起作用。
日志为我提供了从 plist 加载的正确值:47.572132 和 7.579397
自从我两周前开始编写objective-c以来,请保持你的答案尽可能简单;-)
h.文件:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "DetailViewController.h"
#import "Annotation.h"
@interface MapViewController : UIViewController<CLLocationManagerDelegate> {
IBOutlet MKMapView *singlemapview;
}
@property (nonatomic, retain) NSArray *data;
@property int selectedBuilding;
@property (strong, nonatomic) CLLocationManager *location;
@property float longitude;
@property float latitude;
@end
m.文件:
#import "MapViewController.h"
@interface MapViewController ()
@end
@implementation MapViewController
@synthesize data;
@synthesize selectedBuilding;
@synthesize location, latitude, longitude;
- (void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *dataItem = [data objectAtIndex:selectedBuilding];
latitude = [[dataItem objectForKey:@"Latitude"] floatValue];
longitude = [[dataItem objectForKey:@"Longitude"] floatValue];
NSLog (@"%f",latitude);
NSLog (@"%f",longitude);
MKCoordinateRegion startregion = { {0.0, 0.0}, {0.0, 0.0} };
startregion.center.latitude = latitude;
startregion.center.longitude = longitude;
startregion.span.latitudeDelta = 0.005;
startregion.span.longitudeDelta = 0.005;
[singlemapview setMapType:MKMapTypeSatellite];
[singlemapview setZoomEnabled:YES];
[singlemapview setScrollEnabled:YES];
[singlemapview addAnnotation:singlebuilding];
[singlemapview setRegion:startregion];
}
我的应用程序在viewDidLoad或viewWillAppear中调用setRegion方法时具有完全相同的行为。 但是,在viewDidAppear中调用它纠正了这个问题。 希望这有帮助。
我现在可以通过使用 -(void)viewWillAppear:(BOOL)animated
函数而不是使用 -(void)viewDidLoad
来解决我的问题
据我现在了解:
-
ViewDidLoad
在新视图打开之前(segue 动画开始之前)调用一次。但是,要正确绘制地图仍然为时已晚。 - 每次视图出现在屏幕上后(在 segue 动画结束后),都会调用
ViewDidAppear
。 -
ViewWillApper
在打开新视图之前(在 segue 动画之前)完全调用和计算。这就是为什么当你有地图时它可以正常工作的原因。