iOS动画-自动布局(二)

效果图

iOS动画-自动布局(二)_第1张图片
packing.gif

点击cell,弹出对应图片,一秒后收回。

核心代码

  • 初始约束
//imageView的centerx与视图控制器view的centerx一样。
let conX = imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
//imageView的底部相比视图控制器view的底部下沉imageView.frame.width的高度。
let conBottom = imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: imageView.frame.width)
//imageView的宽等于1/3的视图控制器view的宽度
let conWidth = imageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.33, constant: -50.0)
//imageView的宽和高相等。
let conHeight = imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor)
//添加约束
NSLayoutConstraint.activate([conX, conBottom, conWidth, conHeight])
//更新约束
view.layoutIfNeeded()

NSLayoutAnchor对于创建公共约束来说是非常方便的。
conWidth的constant等于-50是为了弹出的时候有一个由小变大的效果,所以先减少50.

  • 弹出动画
    修改约束使视图显示
UIView.animate(withDuration: 0.8,
               delay: 0.0,
               usingSpringWithDamping:  0.4,
               initialSpringVelocity: 0.0,
               animations: {
     //修改底部约束
    conBottom.constant = -imageView.frame.size.height/2
    //修改宽度约束,从-50 到 0,此时宽度恢复到1/3的view宽度
    conWidth.constant = 0.0
    //更新约束
    self.view.layoutIfNeeded()
}, completion: nil)
  • 收起动画
    修改约束跟初始一样。并在动画完成时,移除视图。
UIView.animate(withDuration: 0.8,
               delay: 1.0,
               usingSpringWithDamping: 0.4,
               initialSpringVelocity: 0.0,
               animations: {
                conBottom.constant = imageView.frame.width
                conWidth.constant = -50.0
                self.view.layoutIfNeeded()
}, completion: { _ in
    imageView.removeFromSuperview()
})

代码地址https://github.com/chenruiming/AnimatingConstraints

你可能感兴趣的:(iOS动画-自动布局(二))