前言:AutoLayout定义了View的位置,也就是说,在Auto Layout的工程里,如果不修改约束本身,在视图重新绘制的时候,还会回到最开始的位置。AutoLayout中的动画与视图的位置和大小有关。
先看看效果
实现过程
在Storyboard上拖拽一个UIImageview。设置约束为:水平垂直正中心,大小很定100*100
拖拽Imageview以及Constraint为Outlet
注意拖拽Y相关的约束,也就是这个
对应代码
1 | @IBOutlet weak var imageview: UIImageView! @IBOutlet weak var yConstraints: NSLayoutConstraint!
|
登入後複製
在viewDidload中设置imageview的初始状态
1 | yConstraints.constant = yConstraints.constant - CGRectGetHeight(UIScreen.mainScreen().bounds)/2 self.imageview.alpha = 0.0; self.imageview.transform = CGAffineTransformMakeScale(0.1, 0.1) self.view.layoutIfNeeded();
|
登入後複製
ViewWillAppear中创建动画
1 | yConstraints.constant = yConstraints.constant + CGRectGetHeight(UIScreen.mainScreen().bounds)/2 UIView.animateWithDuration(1.0, animations: { () -> Void in self.imageview.alpha = 1.0 self.imageview.transform = CGAffineTransformIdentity self.view.layoutIfNeeded() })
|
登入後複製
原理
原理比较简单,就是利用修改约束NSLayoutConstraint中的属性constant,然后调用layoutIfNeeded来实现动画。注意,属性multiplier目前(iOS 8.4)还是只读的,不能修改。但是可以通过关系view1.property = view2.property * multiplier + constant进行转换。
纯代码的AutoLayout动画
上述动画用纯代码实现
1 | class ViewController: UIViewController { var imageview:UIImageView? weak var yConstraint:NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad()
|
登入後複製
定位Constraints
设置属性identifier
1 | yConstraint.identifier = "identifier"
|
登入後複製
然后在过滤,定义到这个Constraints,
1 | let constraint = filter(self.view.constraints() as ! [NSLayoutConstraint], { (constraint:NSLayoutConstraint) -> Bool in return constraint.identifier == "identifier" }).first
|
登入後複製