繁体   English   中英

iOS:动画UIButton的文本位置不起作用

[英]iOS: Animating text position of UIButton doesn't work

当按下“错误答案”按钮时,我希望按钮的文本“消失”。

在我的问题 - 演示代码中,我的项目有两个按钮,一个带有插座'myBtn'而没有任何动作,另一个带有TouchUpInside动作。 动作处理程序如下所示:

- (IBAction)goPressed:(UIButton*)sender {

//UILabel *lbl = self.myBtn.titleLabel;
UILabel *lbl = sender.titleLabel;
[UIView animateWithDuration:1.0
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     lbl.center = CGPointMake(lbl.center.x-60, lbl.center.y);
                     lbl.alpha = 0;
                 }
                 completion:nil];
}

我试图动画两个属性:'alpha'从1到0,文本位置向左移动60个点。

如果我取消注释第一个“UILAbel”行并注释第二个,那么按下按钮会在第二个按钮中运行一个漂亮的动画。

但是,如果我将代码保留为显示,尝试为按下的按钮本身设置动画,则alpha动画效果很好,但位置不会改变。

任何帮助将非常感谢!

我在iOS7上看到过这种问题。 在IBAction中运行良好的动画在iOS7上不起作用。 我不得不将所有动画代码移动到另一个方法,并在延迟后调用选择器。 如果你这样做,你的代码将正常工作 -

- (IBAction) goPressed:(UIButton*)sender {
[self performSelector:@selector(animateButton:) withObject:sender afterDelay:0.1];
}

- (void) animateButton:(UIButton *) button{
UILabel *lbl = button.titleLabel;
[UIView animateWithDuration:1.0
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseOut
                 animations:^{
                     lbl.center = CGPointMake(lbl.center.x-60, lbl.center.y);
                     lbl.alpha = 0;
                 }
                 completion:nil];
}

你的问题是将UIButtonUILabel混合在一起。

在这种情况下,方法参数(UIButton*)sender引用UIButton 原因UILabel *lbl = sender.titleLabel; 不起作用是因为senderUIButton引用。 要访问标签对象,必须引用该UILabel嵌入UIButton通过hirarchy sender > UIButton > UILabel

所以你应该使用的代码是:

UIButton *button = sender;
UILabel *lbl = sender.titleLabel;
[UIView animateWithDuration:1.0
                  delay:0.0
                options:UIViewAnimationOptionCurveEaseOut
             animations:^{
                 lbl.center = CGPointMake(lbl.center.x-60, lbl.center.y);
                 lbl.alpha = 0;
             }
         completion:nil];
}

出现代码的原因是因为alphaUIButtonUILabel的属性。 因此即使您错误地重新sender也会有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM