0%

[swift] 製作動畫

目標結果如圖

  • 首先先把最後所有按鈕要放的位置擺好
  • 把每個按鈕跟ViewController做對應 ```swift
    @IBOutlet weak var backgroundImageView: UIImageView!
    @IBOutlet weak var fbButton: UIButton!
    @IBOutlet weak var twitterButton: UIButton!
    @IBOutlet weak var messageButton: UIButton!
    @IBOutlet weak var mailButton: UIButton!
1
2
3
4
5
6
7
8
9
10
11

* 接著用CGAffineTransformMakeTranslation的方式將所有按鈕移到動畫的起始位置,
這邊解釋一下程式中那些數字怎麼決定的,CGAffineTransformMakeTranslation需要給定x y值,如果(0, -300)表示x軸不動,Y軸比原本你在StoryBoard放的位置還要**<span style="color: red;">往上</span>**移300個點的位置,反之(0, 300)則表示比原本擺放的位置**<span style="color: red;">往下</span>**移動300點 ```swift
override func viewDidLoad() {
super.viewDidLoad()
self.fbButton.transform = CGAffineTransformMakeTranslation(0, -300)
self.messageButton.transform = CGAffineTransformMakeTranslation(0, -364)
self.mailButton.transform = CGAffineTransformMakeTranslation(0, 300)
self.twitterButton.transform = CGAffineTransformMakeTranslation(0, 364)
}

  • 接著大家測試一下程式,應該會發現東西的確是跑出螢幕了,接著在viewDidAppear補上以下程式碼就大功告成了!! ```swift
    override func viewDidAppear(animated: Bool) {

      super.viewDidAppear(animated)
    
          //動畫,分成兩個區塊是因為有快有慢,差別在於delay多久再發動,usingSpringWithDamping是彈跳的反作用力,越小越劇烈
      UIView.animateWithDuration(0.9, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: nil, animations: {
          //跑回原來的點
          let translate = CGAffineTransformMakeTranslation(0, 0)
          self.messageButton.transform = translate
          self.twitterButton.transform = translate
      }, completion: nil)
      UIView.animateWithDuration(0.9, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: nil, animations: {
          let translate = CGAffineTransformMakeTranslation(0, 0)
          self.fbButton.transform = translate
          self.mailButton.transform = translate
      }, completion: nil)
    

    }