监听UIView animation的动画过程

今天遇到个场景,是在UIView做动画效果期间显示进度和百分比,之后发现UIView包括block方法在内的都没有动画移动过程之间的回调,查阅后可使用NSTimer来获取

    _progressTimer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(testAction) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:_progressTimer forMode:NSRunLoopCommonModes];

_progressTimer是个全局的timer,添加到NSRunLoop里后通过它的消息处理机制来监听目标属性的改变,testAction是执行方法

- (void)testAction

{

    CALayer *layer = _progressView.layer.presentationLayer;

    _yesLabel.text = [NSString stringWithFormat:@"我喜欢 %.2f%@", (100*layer.bounds.size.width)/ScreenSize().width, @"%"];

    _noLabel.text = [NSString stringWithFormat:@"一般 %.2f%@", 100 - (100*layer.bounds.size.width)/ScreenSize().width, @"%"];

}

在testAction方法里,通过presentationLayer属性来获取到对象的CALayer,之后处理想要的结果,记得在实行完毕后干掉timer,下面是动画执行的方法

    [UIView animateWithDuration:1

                     animations:^{

                         _progressView.frame = CGRectMake(0, 0, self.frame.size.width/100.0*self.progress, self.frame.size.height);

    }

                     completion:^(BOOL finished){

                        if (_progressTimer) {

                             [_progressTimer invalidate];

                             _progressTimer = nil;

                         }

    }];

猜你喜欢

转载自blog.csdn.net/xiaobo0134/article/details/82385078