遇到一些问题,搜索了一些类似的问题但却无法解决问题。我有一个简单的按钮动画,我在我制作的实用程序类中使用我的项目。问题是按钮代码在动画完成之前执行。
实用程序中的动画代码class.m:
+(void)buttonBobble:(UIButton *)button{
button.transform = CGAffineTransformMakeScale(0.8, 0.8);
[UIView beginAnimations:@"button" context:nil];
[UIView setAnimationDuration:.5];
button.transform = CGAffineTransformMakeScale(1, 1);
[UIView commitAnimations];
}
我尝试确保动画在任何按钮触发代码之前完成:
[UIView animateWithDuration:0.0f delay:0.0f options: UIViewAnimationOptionTransitionNone animations:^{
[Utilities buttonBobble:sender];
}completion:^(BOOL finished){
//Do stuff
}];
即使有效,我希望将其抽象出来,我可以做到这样的事情:
if([Utilities buttonBobble:sender]){
//Make it send a BOOL so when it's done I execute stuff like normal
}
欢迎任何想法。
答案 0 :(得分:5)
更改您的实用程序方法以获取一个完成块,该块封装了按钮在完成浮动时需要执行的操作:
+(void)buttonBobble:(UIButton *)button
actionWhenDone:(void (^)(BOOL))action
{
button.transform = CGAffineTransformMakeScale(0.8, 0.8);
[UIView animateWithDuration:0.5f animations:^{
button.transform = CGAffineTransformMakeScale(1, 1);
}
completion:action];
}
在原始按钮操作方法中,您传递该操作块而不是直接在方法中运行代码:
- (IBAction)buttonAction:(id)sender
{
[Utilities buttonBobble:sender
actionWhenDone:^(BOOL finished){
// Your code here
}];
// Nothing here.
}
作为设计说明,您还可以考虑将该实用程序方法放在UIButton
上的类别中:
@implementation UIButton (JMMBobble)
- (void)JMMBobbleWithActionWhenDone:(void (^)(BOOL))action
{
self.transform = CGAffineTransformMakeScale(0.8, 0.8);
[UIView animateWithDuration:0.5f animations:^{
self.transform = CGAffineTransformMakeScale(1, 1);
}
completion:action];
}
然后行动看起来像
- (IBAction)buttonAction:(id)sender
{
[sender JMMBobbleWithActionWhenDone:^(BOOL finished){
// Your code here
}];
}
答案 1 :(得分:0)
我喜欢这样做,特别是如果动画将彼此嵌套我发现如果我使用NSTimers
将其拆分,我的代码更容易编写/读取。您可以看到计时器使用与动画时间相同的间隔。
-(void)fadeOutText{
[UIView beginAnimations:@"fadeOutText" context:NULL];
[UIView setAnimationDuration:1.0];
someButton.titleLabel.alpha = 0.0f;
[UIView commitAnimations];
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(changeTextAndFadeIn)
userInfo:nil
repeats:NO];
}
-(void)changeTextAndFadeIn{
[someButton setTitle:@"Testing" forState:UIControlStateNormal];
[UIView beginAnimations:@"fadeInText" context:NULL];
[UIView setAnimationDuration:1.0];
someButton.titleLabel.alpha = 1.0f;
[UIView commitAnimations];
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(finishedFading)
userInfo:nil
repeats:NO];
}
-(void)changeTextAndFadeIn{
//Code to be executed after text has faded out / changed / faded in.
}