【问题标题】:MKMapView not properly centered the first time it appears (but works thereafter)MKMapView 第一次出现时未正确居中(但此后有效)
【发布时间】:2013-09-16 04:37:27
【问题描述】:

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

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

下面的代码是在detail controller的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];
}

【问题讨论】:

    标签: ios cllocation mkmapview


    【解决方案1】:

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

    【讨论】:

    • 我试过了,但它仍然会导致完全相同的行为...在详细视图(mapView)的初始呈现中,区域定位和大小不起作用...无论如何感谢您的尝试。 ..仍然需要解决方案
    • ps。我已经检查了第一次打开视图时区域和坐标的值是否正确,即问题不在于
    • 我已经解决了...关键是将代码放在 viewDidAppear 中,而不是 viewWillAppear 或 viewDidLoad 中(并且还要制作动画:NO)...否则第一次调用 setRegion到一个尚不存在的mapView...我想另一种方法可能是在主控制器中的prepareForSegue中创建一个MKMapView并将其传递给detailView的属性mapView...
    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多