在正弦波路径上为UIView设置动画

JoJ*_*oJo 3 animation cocoa-touch ios

在此输入图像描述

你会如何沿着正弦波路径移动UIView?理想情况下,当UIView离开屏幕并释放它时,我能够停止动画.我看到UIView-> animateWithDuration一次只能对一个属性进行动画处理,但这似乎是两个独有的事情同时发生:它向右移动并且向上/向下移动.

pau*_*lvs 8

你可以用一个简单的方法来做到这一点CAKeyframeAnimation.

override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UIView(frame: CGRect(x: 10, y: 100, width: 50, height: 50))
    myView.backgroundColor = UIColor.cyan
    view.addSubview(myView)

    let animation = CAKeyframeAnimation()
    animation.keyPath = "position"
    animation.duration = 60  // 60 seconds
    animation.isAdditive = true // Make the animation position values that we later generate relative values.

    // From x = 0 to x = 299, generate the y values using sine.
    animation.values = (0..<300).map({ (x: Int) -> NSValue in
        let xPos = CGFloat(x)
        let yPos = sin(xPos)

        let point = CGPoint(x: xPos, y: yPos * 10)  // The 10 is to give it some amplitude.
        return NSValue(cgPoint: point)
    })
    myView.layer.add(animation, forKey: "basic")
}
Run Code Online (Sandbox Code Playgroud)