【问题标题】:How would one animate UILabel text property with CoreAnimation in Swift?如何在 Swift 中使用 CoreAnimation 为 UILabel 文本属性设置动画?
【发布时间】:2016-04-11 08:48:19
【问题描述】:

我想使用 CoreAnimation 和缓动函数(例如 easeInOutQuad)将 UILabel.text 的值从 0 增加到 100。但似乎 text 属性是不可动画的。那么如何在 CA 的帮助下实现这一点呢?还是我需要自己实现缓动功能并使用 GCD 调用它? 谢谢

附:我想尽可能地坚持 CA。

【问题讨论】:

  • 公平地说,你有一个数字属性,你想要动画并且它的值显示在标签中,并且对于动画的每一帧你希望标签显示 (格式化)内插数值?
  • 是的。这正是我想要实现的目标。
  • @David Rönnqvist 我尝试使用 didSet 观察者为自定义属性设置动画,并在其中更新 UILabel 值,但它也不起作用。

标签: ios swift core-animation uiviewanimation cabasicanimation


【解决方案1】:
class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    var counter = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("animate"), userInfo: nil, repeats: true)
        timer.fire()
    }

    func animate() {
        UIView.transitionWithView(label,
                              duration: 1.0,
                              options: [.CurveEaseInOut],
                              animations: { () -> Void in
                                self.counter += 1
                                self.label.text = "\(self.counter)"
        }, completion: nil)

    }
}

【讨论】:

  • 可能我没有说清楚。我希望值在动画时间增量动画:1..2..3..4...100
  • 尝试设置一个国家属性,并设置一个使用上述代码调用方法的 NSTimer (scheduledTimerWithTimeInterval:),但不是将 Hello World 设置为属性的值。
  • 谢谢 Jasper,但这样我看不到中间值(递增数字)。
  • mra214,我已经编辑了我的帖子。请让我知道这是否可行。它对我有用,但我不能 100% 确定我理解你的问题:)
  • 是的,Jasper,它确实有效,虽然不是我想要的。在您的示例中,缓动函数仅应用于相邻值,但我需要将其应用于整个动画,但我想我可以解决它。所以我接受你的回答。 (目前 :))。谢谢。
【解决方案2】:

您可以使用核心动画来实现。您可以将动画添加到标签。试试下面的

CATransition *textAnimation = [CATransition animation];
textAnimation.type = kCATransitionMoveIn;
textAnimation.duration = 0.5;
textAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[numLabel.layer addAnimation:textAnimation forKey:@"changeTextTransition"];

您可以在添加动画后随时更改标签文本,它会动画。

numLabel.text = "1";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多