我正在实现一个方法,它有一个名为animated
的布尔参数,类似于许多UIKit方法。为了简化实现,我想写一下:
- (void)showElement:(BOOL)animated
{
CGFloat duration = animated ? 0.25 : 0;
[UIView animateWithDuration:duration animations:^{
// animation code
} completion:^(BOOL finished) {
// completion code
}];
}
这是正确的还是有必要两次写出UI代码?
- (void)showElement:(BOOL)animated
{
if (animated) {
[UIView animateWithDuration:0.25 animations:^{
// animation code
} completion:^(BOOL finished) {
// completion code
}];
} else {
// animation code
// completion code
}
}
答案 0 :(得分:3)
我这样写了 - 它首先创建了块,然后将它提供给UIView动画方法或者自己执行:
- (void) showElement:(BOOL) animated
{
void (^animations)(void) = ^{
// animation code
};
if(animated)
{
[UIView animateWithDuration:0.25 animations:animations];
}
else
{
animations();
}
}
编辑:您也可以对完成块执行相同的操作