今天遇到個場景,是在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:@"1般 %.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;
}
}];