MKMapView第一次出现时没有正确居中(但之后有效)

时间:2013-09-16 04:37:28

标签: ios cllocation mkmapview

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

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

下面的代码位于详细控制器的viewWillAppear方法中,但如果将其放在viewDidLoad中,或者甚至放在主视图控制器的prepareForSegue方法中,效果都是相同的。

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

另一位SO用户提出了同样的问题(Cannot get UIMapView to "zoom"/setRegion: when the map is loaded for the first time),但没有一个答案可以解决问题。

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];
}

1 个答案:

答案 0 :(得分: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];