2016-02-29 100 views
1

enter image description here在正弦波路徑上動畫UIView

如何讓UIView沿着正弦波路徑移動?理想情況下,我可以在UIView關閉屏幕並釋放它時停止動畫。我發現UIView-> animateWithDuration一次只能在一個屬性上進行動畫製作,但這似乎是兩個獨有的事情同時發生的:它正在向右移動,並向上/向下移動。

回答

4

你可以用簡單的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") 
}