我需要在iOS的Objective-C中创建移动标签的动画。动画应该在用户点击某个按钮时出现。此外,我需要禁用任何UI交互,而动画正在进行中。我是这样做的:
1。在视图控制器的viewDidLoad方法中创建UILabel对象,将所有必需的字段设置为适当的值,并使其隐藏:
plusScoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 50.0f, 50.0f)];
plusScoreLabel.text = @"+10";
plusScoreLabel.textColor = [UIColor colorWithRed:12.0/255.0 green:144.0/255.0 blue:51.0/255.0 alpha:1.0];
plusScoreLabel.hidden = YES;
plusScoreLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:plusScoreLabel];
uiInteractionsDisabled = NO;
2。然后我调用animateWithDuration:animation:completion方法在按钮按下的动作上像这样:
uiInteractionsDisabled = YES;
[plusScoreLabel setCenter:CGPointMake(buttonToChoose.center.x, buttonToChoose.center.y)];
plusScoreLabel.hidden = NO;
[UIView animateWithDuration:0.5f animations:^{
plusScoreLabel.center = CGPointMake(buttonToChoose.center.x, buttonToChoose.center.y - 50.0f);
} completion:^(BOOL finished) {
plusScoreLabel.hidden = YES;
}];
3。向每个IBAction方法添加以下检查:
if (uiInteractionsDisabled == YES) {
return;
}
这个方法有什么问题吗?也许有更好的方法来实现这种行为?
你的解决方案没有问题。如果您想要一些特别的东西,您可以创建CABasicAnimation的子类并覆盖其中的两个方法:
/* Called when the animation begins its active duration. */
- (void)animationDidStart:(CAAnimation *)anim;
/* Called when the animation either completes its active duration or
* is removed from the object it is attached to (i.e. the layer). 'flag'
* is true if the animation reached the end of its active duration
* without being removed. */
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag;
另外,你可以给子类添加两个block属性:
@property (nonatomic, copy) void (^startBlock)(void) ;
@property (nonatomic, copy) void (^finishBlock)(void) ;
并执行覆盖方法中的块:
- (void)animationDidStart:(CAAnimation *)anim{
if (_startBlock){
_startBlock();
}
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
if (_finishBlock){
_finishBlock();
}
}
之后,你可以像这样使用你的自定义动画对象:
MyCustomAnimation* anim = [MyCustomAnimation animationWithKeyPath:@"position"];
anim.startBlock = ^{uiInteractionsDisabled = YES;};
anim.finishBlock = ^{uiInteractionsDisabled = NO;};
[anim setFromValue:[NSValue valueWithCGPoint:CGPointMake(buttonToChoose.center.x, buttonToChoose.center.y)]];
[anim setToValue:[NSValue valueWithCGPoint:CGPointMake(buttonToChoose.center.x, buttonToChoose.center.y - 50.0f)]];
[anim setDuration:0.5];
[plusScoreLabel.layer addAnimation:anim forKey:@"translationAnimation"];
我希望你学到了一些新的东西