iOS storyboard 實現動畫,不用將檢視拖到程式碼中
阿新 • • 發佈:2019-01-26
實現思路
-
通過改變Constraint.constant的值來改變檢視的位置
實現步驟
在storyboard中設定好佈局
將要修改的Constraint連線成屬性到程式碼中
在需要動畫的地方加上程式碼
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()
}
}
}