【问题标题】:iOS: Animating text position of UIButton doesn't workiOS:UIButton 的动画文本位置不起作用
【发布时间】:2013-10-14 06:25:40
【问题描述】:

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

在我的问题演示代码中,我的项目有两个按钮,一个带有出口“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 的动画效果很好,但位置没有改变。

任何帮助将不胜感激!

【问题讨论】:

  • 试试 sender.currenttitle
  • 为什么不只是为整个按钮设置动画/将文本设置为“”?
  • CurrentTitle 是 NSString,所以我无法为其位置设置动画。

标签: ios animation uibutton


【解决方案1】:

我在 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];
}

【讨论】:

  • 非常感谢凯达。它就像一个魅力!即使有 0.05 的延迟。这很有趣,因为即使给动画本身添加几秒钟的延迟也不能解决问题......
  • @Kedar 这是一个错误吗?因为这帮助我什至不知道为什么=/
【解决方案2】:

您的问题是将UIButtonUILabel 混淆。

在这种情况下,方法参数(UIButton*)sender 引用了UIButtonUILabel *lbl = sender.titleLabel; 不起作用的原因是 senderUIButton 引用。要访问标签对象,您必须通过层次结构sender > UIButton > UILabel 引用嵌入在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];
}

代码出现异常的原因是alphaUIButtons 和UILabels 的属性。因此,即使您错误地引用了sender,它也会起作用。

【讨论】:

  • 感谢安德鲁的回复,但我不明白你的意思。我不会混淆我的代码中的任何内容。发件人是一个 UIButton,我正确地使用了它的 titleLabel。我会检查 Kedar 的解决方案并尽快报告
猜你喜欢
  • 1970-01-01
  • 2018-01-02
  • 2021-03-11
  • 2021-03-21
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多