为什么UIView:animateWithDuration会立即完成?
我有一个MKPointAnnotation
的子类,我在iOS 4上运行以下方法:
- (void)animate { [UIView animateWithDuration: 3.0 delay:1.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{ CLLocationCoordinate2D loc = CLLocationCoordinate2DMake([self coordinate].latitude + 0.001, [self coordinate].longitude + 0.001); [self setCoordinate:loc]; } completion:^(BOOL finished) { NSLog(@"Is completed"); }]; }
通过单击UIBarButtonItem
来调用它。
我期望看到我的注释穿过MKMapView
。 然而,当我调用这样的方法时,我所看到的只是最终安息位置的注释:
[mapView addAnnotation:myAnnotation]; [myAnnotation animate]; [myAnnotation release];
只有当我调用这样的方法时才会出现预期的动画:
[mapView addAnnotation:myAnnotation]; [myAnnotation performSelector:@selector(animate) withObject:nil afterDelay:0.5]; [myAnnotation release];
请注意,如果’afterDelay’较小,例如<0.1s,则会出现意外行为。
任何想法为什么会这样?
动画最终作用于MKAnnotationView
,而不是MKAnnotation
。 向MKMapView
添加注释并不一定意味着将很快添加相应的视图。
因此,如果在将相应的MKAnnotationView
添加到MKMapView
之前尝试为MKAnnotation设置动画,则会出现疯狂的行为。
解决方案是只有在知道其相应的MKAnnotationView已添加到MKView后才动画MKAnnotation。 您可以通过使用MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
来触发您的动画。