在计时器

时间:2017-12-11 11:26:32

标签: ios animation uiview timer

我制作的应用程序从数字10开始每秒倒数。倒计时动画。这是代码:

import UIKit

class ViewController: UIViewController {

    var startNumber = 10

    lazy var numberLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = label.font.withSize(160)
        label.textColor = .lightGray
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        view.addSubview(numberLabel)

        NSLayoutConstraint.activate([
            numberLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            numberLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
            ])

        _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (time) in

            self.numberLabel.text = String(self.startNumber)
            self.startNumber -= 1

            UIView.animate(withDuration: 0.99, animations: {
                self.numberLabel.alpha = 0
            }, completion: { (true) in
                self.numberLabel.alpha = 1
            })

        }
    }

}

如果UIView和Timer间隔相等,则倒计时显示数字的不均匀动画。这就是为什么在代码中UIView间隔被设置为0.99而不是1来显示每个数字的动画倒计时。因为你可以看到数字" flick"动画仍然不是很平滑。在一毫秒内但我认为这是因为间隔设置为0.99而不是1.

我的问题是:

1)为什么在UIView和Timer上设置相等的间隔导致奇数倒计时动画?

2)倒数计数是否仍然倒数每秒或0.99秒?

2 个答案:

答案 0 :(得分:1)

将代码更改为

 _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (time) in


        self.startNumber -= 1

         self.numberLabel.alpha = 1

        UIView.setAnimationCurve(UIViewAnimationCurve.easeInOut)

        UIView.animate(withDuration: 1, animations: {

            self.numberLabel.text = String(self.startNumber)
            self.numberLabel.alpha = 0
        }, completion: { (true) in

        })

    }

答案 1 :(得分:1)

1)为什么在UIView和Timer上设置相等的间隔导致奇数倒计时动画?

Ans:设置相同的时间时,上一个动画肯定会与新动画重叠。所以最好放一个较短的时间。甚至低于0.99

2)倒数计数是否仍然倒数每秒或0.99秒?

Ans:无论动画计时器如何,都会在每秒触发倒计时