为什么UIView:animateWithDuration立即完成? [英] Why does UIView:animateWithDuration complete immediately?
问题描述
我有一个 MKPointAnnotation
的子类,它具有在iOS 4上运行的以下方法:
I have a subclass of MKPointAnnotation
with the following method which I run on 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 $进行调用c $ c>。
我希望看到我的注释在 MKMapView
上移动。但是,当我这样调用方法时,我所看到的只是注释在其最终的静止位置:
I expect to see the my annotation travel across a MKMapView
. However all I see is the annotation in its final resting place when I call the method like this:
[mapView addAnnotation:myAnnotation];
[myAnnotation animate];
[myAnnotation release];
仅当我调用如下方法时,才会出现预期的动画:
The intended animation only occurs if I call the method like this:
[mapView addAnnotation:myAnnotation];
[myAnnotation performSelector:@selector(animate) withObject:nil afterDelay:0.5];
[myAnnotation release];
请注意,如果 afterDelay较小,则会出现意想不到的行为,例如< 0.1s。
Note that I get the unintended behavior if the 'afterDelay', is smaller e.g. < 0.1s.
为什么会出现这种情况?
Any ideas why this could be the case?
推荐答案
动画最终会作用在 MKAnnotationView
上,而不是作用在 MKAnnotation
上。在 MKMapView
中添加注释并不一定意味着很快就会添加相应的视图。
The animation ultimately acts on the MKAnnotationView
, not the MKAnnotation
. Adding an annotation to a MKMapView
does not necessarily mean that the corresponding view will be added any time soon.
因此如果您尝试为MKAnnotation设置动画,然后将其相应的 MKAnnotationView
添加到 MKMapView
,则会出现疯狂的行为。
Therefore you get crazy behaviour if you attempt to animate a MKAnnotation before its corresponding MKAnnotationView
has been added to the MKMapView
.
解决方案是仅在知道MKAnnotation对应的MKAnnotationView已添加到MKView后对其进行动画处理。您可以通过使用 MKMapViewDelegate
-(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
触发动画。
The solution is to only animate a MKAnnotation once you know its corresponding MKAnnotationView has been added to MKView. You can know this by using MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
to trigger your animation.
这篇关于为什么UIView:animateWithDuration立即完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!