3

我有一个主从应用程序设置,主是一个 UITableView,其中包含一个列表,每个列表都有一个位置(纬度和经度)。当用户点击一个列表项时,他们会得到一个包含 MKMapView 的详细视图,上面有相关的注释。

设置要显示的区域的代码如下。然而,当用户第一次点击列表中的一个项目时,mapView 显示了一半的世界,显然以 0,0 为中心。放置的注释(代码未显示)在适当的位置,但中心和比例都是错误的。如果用户返回到主列表并再次点击该项目(或点击任何其他项目),则地图正确居中并调整大小,并且代码有效 v. 我无法确定 mapView 为什么第一次没有正确响应 setRegion 调用时间。

下面的代码是在detail controller的viewWillAppear方法中,但是放在viewDidLoad中效果是一样的,甚至放在主视图控制器的prepareForSegue方法中也是一样的。

我还尝试将区域的初始声明更改为不同的坐标,认为这可能是问题所在,但事实并非如此......无论我在初始化区域时使用什么值,或者即使我不使用,行为都是相同的设置它的初始值。

另一个 SO 用户问了同样的问题(无法让 UIMapView 到“缩放”/setRegion:第一次加载地图时),但没有一个答案能解决问题。

fwiw,详细视图控制器被声明为 MKMapView 委托,并被分配为 mapView 的委托,但我还没有实现任何委托方法(它也是一个 MKAnnotation 委托,我已经实现了 mapView:viewForAnnotation)

任何关于我需要把这段代码放在哪里的指导,或者我需要实现什么样的委托方法,以便它会在 mapView 第一次出现时引起适当的居中和缩放,将不胜感激。

这是代码:

 CLLocationCoordinate2D coordinates = CLLocationCoordinate2DMake([self.listing.latitude doubleValue], [self.listing.longitude doubleValue]);
MKPointAnnotation *selectedListingAnnotation=[[MKPointAnnotation alloc] init];
selectedListingAnnotation.coordinate=coordinates;

MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center = coordinates;
region.span.longitudeDelta = 0.02f;
region.span.latitudeDelta  = 0.02f;
[self.mapView setRegion:region animated:YES];
if (selectedListingAnnotation) {
    [self.mapView addAnnotation:selectedListingAnnotation];
}
4

1 回答 1

2

viewDidLoad方法中,添加annotations到 后mapview,使用以下代码进行居中,

CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([self.listing.latitude doubleValue], [self.listing.longitude doubleValue]);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.18;
span.longitudeDelta=0.18;    
region.span=span;
region.center=coordinate;
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
于 2013-09-16T04:58:27.397 回答