1. 程式人生 > >iOS storyboard 實現動畫,不用將檢視拖到程式碼中

iOS storyboard 實現動畫,不用將檢視拖到程式碼中

實現思路

通過改變Constraint.constant的值來改變檢視的位置

實現步驟

  1. 在storyboard中設定好佈局
    這裡寫圖片描述

  2. 將要修改的Constraint連線成屬性到程式碼中
    這裡寫圖片描述

  3. 在需要動畫的地方加上程式碼

    self.centerYConstraint.constant = 要移動的距離
    UIView.animate(withDuration: 動畫的時間) {
        self.view.layoutIfNeeded()
    }

完整程式碼

/// Swift3.1
import UIKit

class ViewController
: UIViewController { @IBOutlet weak var centerYConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func touchesBegan(_ touches: Set<UITouch>, with event
: UIEvent?)
{ self.centerYConstraint.constant = 200 UIView.animate(withDuration: 1.5) { self.view.layoutIfNeeded() } } }