【问题标题】:Animate meteor traveling from top to bottom in Swift 3在 Swift 3 中动画流星从上到下移动
【发布时间】:2017-05-02 22:51:47
【问题描述】:

我想要一个红色圆圈的图像从屏幕顶部移动到底部,就好像它是穿过屏幕的流星一样。它确实移动了,但它在一毫秒内移动,没有动画。如何让它像有尾巴的流星一样平稳移动?

class ViewController: UIViewController {

    let meteorImage = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.meteorImage.backgroundColor = .clear
        self.meteorImage.frame = CGRect(x: 50, y: 0, width: 50, height: 50)
        self.meteorImage.isHidden = false
        self.meteorImage.image = #imageLiteral(resourceName: "success")
        view.addSubview(self.meteorImage)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func buttonPressed(_ sender: UIButton) {
        let totalHeight = Int(view.frame.height)
        var currentHeight = 0

        while currentHeight < totalHeight {
            self.meteorImage.backgroundColor = .clear
            self.meteorImage.frame = CGRect(x: 50, y: currentHeight, width: 50, height: 50)
            self.meteorImage.isHidden = false
            self.meteorImage.image = #imageLiteral(resourceName: "success")
            view.addSubview(self.meteorImage)
            currentHeight += 1
        }
    }
}

【问题讨论】:

  • 考虑使用 UIKit Dynamics。

标签: swift animation swift3 uiimageview uiimage


【解决方案1】:

动画必须通过 animate 调用来完成。

这是一种制作动画的简单方法。

UIView.animate(withDuration: 0.1, animations: { 
   // Apply Changes to frame.
})

还请考虑:不要执行 while 循环,只需设置流星帧的最终位置并将持续时间设置为您希望它花费的时间。

let newFrame= CGRect(x: 50, 
                     y: currentHeight, 
                     width: 50, 
                     height: 50)

UIView.animate(withDuration: 3.0, animations: { 
   // Apply Changes to frame.
   self.meteorImage.frame = newFrame
})

如果您想让动画更复杂,您可以查看 UIView 上的关键帧动画。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    相关资源
    最近更新 更多