我试图MKMapView
在选择注释后居中。我也启用canShowCallout
了,但似乎 iOS 首先显示标注(当它不适合屏幕时移动)然后移动地图,导致标注在屏幕上不完全可见。
在渲染和显示标注的位置之前,如何使地图居中?
我试图MKMapView
在选择注释后居中。我也启用canShowCallout
了,但似乎 iOS 首先显示标注(当它不适合屏幕时移动)然后移动地图,导致标注在屏幕上不完全可见。
在渲染和显示标注的位置之前,如何使地图居中?
我想完成同样的事情并最终做了以下事情。
在开始之前请注意:我知道解决方案非常丑陋!...但是,嘿,它有效。
注意:我的目标是 iOS 9,但它应该适用于早期版本的 iOS:
好的,我们开始:
@property(nonatomic, assign, getter=isPinCenteringOngoing) BOOL pinCenteringOngoing;
mapView:viewForAnnotation:
设置canShowCallout
NO
在mapView:didSelectAnnotationView:
执行以下操作:
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
if([view isKindOfClass:$YOURANNOTATIONVIEWCLASS$.class])
{
if(!self.isPinCenteringOngoing)
{
self.pinCenteringOngoing = YES;
[self centerMapOnSelectedAnnotationView:($YOURANNOTATIONVIEWCLASS$ *)view];
}
else
{
self.pinCenteringOngoing = NO;
}
}
}
在mapView:didDeselectAnnotationView:
执行以下操作:
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
if([view isKindOfClass:$YOURANNOTATIONVIEWCLASS$.class])
{
if(!self.isPinCenteringOngoing)
{
view.canShowCallout = NO;
}
}
}
最后创建一个执行实际工作的新方法:
- (void)centerMapOnSelectedAnnotationView:($YOURANNOTATIONVIEWCLASS$ *)view
{
// Center map
CGPoint annotationCenter = CGPointMake(CGRectGetMidX(view.frame), CGRectGetMidY(view.frame));
CLLocationCoordinate2D newCenter = [self.mapView convertPoint:annotationCenter toCoordinateFromView:view.superview];
[self.mapView setCenterCoordinate:newCenter animated:YES];
// Allow callout to be shown
view.canShowCallout = YES;
// Deselect and then select the annotation so the callout is actually displayed
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void)
{
[self.mapView deselectAnnotation:view.annotation animated:NO];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void)
{
[self.mapView selectAnnotation:view.annotation animated:NO];
});
});
}
为了完成我的回答,这里是我在上面的代码中所做的事情以及我这样做的原因的文字说明:
我希望我的回答可能有用。
这是另一个解决方案:
var selectFirstAnnotation = false
在控制器中创建一个新的布尔属性
在注释居中之前将其设置为 true
添加这是在regionDidChangeAnimated
.
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if selectFirstAnnotation == true {
if let annotation = mapView.annotations.first(where: { !($0 is MKUserLocation) }) {
mapView.selectAnnotation(annotation, animated: true)
selectFirstAnnotation = false
}}}
适合我的行为