我正在尝试学习如何使用 MKMapView 并为此创建了一个示例应用程序;但是,在我的代码中,我正在调用以setRegion:animated
更改中心点和跨度,但地图永远不会更新。我在 StackOverflow (SO) 上运行了几个线程,其他人提到了类似的问题并尝试实施他们的解决方案无济于事。
我确保根据我发现的其他 SO 线程在我的代码中尝试的事情:
- 确保我用框架初始化了 MKMapView
- 尝试
setRegion:animated
在主线程上运行方法调用
我在下面包含了我的代码,任何人都可以解释为什么我的 MKMapView 实例不会更新它的视图吗?
编辑:正确的代码如下所示: MK_ViewController.h:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MV_ViewController : UIViewController {
IBOutlet MKMapView *myMapView;
MKCoordinateRegion defaultRegion;
CLLocationCoordinate2D defaultCenter;
MKCoordinateSpan defaultSpan;
}
@end
MK_ViewController.m:
#import "MV_ViewController.h"
@interface MV_ViewController ()
@end
@implementation MV_ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// initialize default map view properties
defaultCenter = CLLocationCoordinate2DMake(33.732894,-118.091718);
defaultSpan = MKCoordinateSpanMake(0.028270, 0.0465364);
// Setup MapView's inital region
defaultRegion = MKCoordinateRegionMake(defaultCenter, defaultSpan);
// create the map view
CGRect screenRect = [[UIScreen mainScreen] bounds];
myMapView = [[MKMapView alloc] initWithFrame:screenRect];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// update map's initial view
[myMapView setRegion:defaultRegion animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
MK_ViewController+MKMapViewDelegate.m:
#import "MV_ViewController.h"
@implementation MV_ViewController (MKMapViewDelegate)
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
MKCoordinateRegion region = mapView.region;
CLLocationCoordinate2D center = region.center;
MKCoordinateSpan span = region.span;
NSLog(@"Center (lat,lon): (%f,%f)",center.latitude,center.longitude);
NSLog(@"Span (lat,lon): (%f,%f)",span.latitudeDelta,span.longitudeDelta);
}
@end