UIView animateWithDuration和UIProgressView setProgress

Nts*_*skX 18 objective-c uiprogressview uiviewanimation ios

我希望UIProgressView在10秒内将我的进度从0变为1.

码:

[UIView animateWithDuration:10.0 animations:^{
    [_myProgressView setProgress:1 animated:YES];
} completion:(BOOL finished)^{
    if (finished) NSLog(@"animation finished);
}];
Run Code Online (Sandbox Code Playgroud)

动画工作正常,但完成后NSLog总是立即调用.

我试过animateWithDuration: withDelay:但延迟没有得到尊重并立即执行.

有谁遇到过同样的问题?

谢谢你的帮助.

小智 38

这是一个老问题,但我仍然在这里发布解决方案.解决方案结果非常简单.你需要做的就是:

[_myProgressView setProgress:1];
[UIView animateWithDuration:10.0 animations:^{
    [_myProgressView layoutIfNeeded];
} completion:^(BOOL finished){
    if (finished) NSLog(@"animation finished");
}];
Run Code Online (Sandbox Code Playgroud)

这里有一个很好的解释为什么事情对你来说不正确:http: //blog.spacemanlabs.com/2012/08/premature-completion-an-embarrassing-problem/

因此,您无法使用setProgress:animated:方法为进度视图设置动画并获得所需的completion块行为.但是,仅progress在块内设置不会为其设置动画,因为progress它不是可动画的属性.

请参阅苹果文档,其中说明了可以设置动画的必要条件: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/clm/UIView/animateWithDuration:动画:

因此,您只需更新progressanimate块外部的属性值,并在animate块内部进行视图布局.

  • 这应该标记为正确的答案. (3认同)

kwa*_*ahn 11

这些答案都没有真正对我有用。我能够获得动画的进展,但由于某种原因,它在开始时有延迟(尤其是持续时间较长)。

对我来说,关键是layoutIfNeeded在动画块内部调用并在执行第二个动画之前等待完成。此代码是从 调用的viewDidLoad。使用以下代码,我能够实现完美流畅的计时器动画。

    // For some reason, the first layoutIfNeeded() needs to be wrapped in an animation block, even though it is supposedly a synchronous call.  Otherwise, the progress just jumps right to 100%
    UIView.animate(withDuration: 0.0, animations: {
        self.progressView.layoutIfNeeded()
    }, completion: { finished in
        self.progressView.progress = 1.0

        UIView.animate(withDuration: self.timerDuration, delay: 0.0, options: [.curveLinear], animations: {
            self.progressView.layoutIfNeeded()
        }, completion: { finished in
            print("animation completed")
        })
    })
Run Code Online (Sandbox Code Playgroud)


Emi*_*lDo 2

我发现一组 UIview 动画和进度视图动画效果更好,并且进度视图动画效果更流畅。如果你只使用动画和progressview动画的组合,它会直接触发,而不考虑UIview动画计时器。

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    timer = [NSTimer scheduledTimerWithTimeInterval: 1.0f
                                             target: self
                                           selector: @selector(updateTimer)
                                           userInfo: nil
                                            repeats: YES];
}


- (void)updateTimer
{
    if (progressView.progress >= 1.0) {
        [timer invalidate];
    }
    [UIView animateWithDuration:1 animations:^{
        float newProgress = [self.progressView progress] + 0.125;
        [self.progressView setProgress:newProgress animated:YES];
    }];
}
Run Code Online (Sandbox Code Playgroud)

随意调整动画时间以实现更好、更平滑的过渡