你如何沿着正弦波路径移动UIView?理想情况下,当UIView离开屏幕并释放它时,我能够停止动画。我看到UIView-> animateWithDuration一次只能在一个属性上制作动画,但这似乎是两个独有的事情同时发生:它向右移动并且它向上/向下移动。 / p>
答案 0 :(得分: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")
}