ios自带自动布局太过繁琐,所以一直采用第三方框架Snapkit的自动布局。NSLayoutAnchor(ios9.0)虽然优化了自动布局,但是感觉还是不够用啊,不知道苹果后续还会不会继续优化。
NSLayoutAnchor与Snapkit简易自动布局与动画对比:
Snapkit写法
yellowView = UIView()
yellowView.backgroundColor = UIColor.yellowColor()
view.addSubview(yellowView)
yellowView.snp_makeConstraints { (make) in
make.left.equalTo(self.view).offset(20)
make.top.equalTo(self.view).offset(20)
make.width.height.equalTo(100)
}
redView = UIView()
redView.backgroundColor = UIColor.redColor()
view.addSubview(redView)
redView.snp_makeConstraints { (make) in
make.left.equalTo(yellowView.snp_right).offset(80)
make.top.equalTo(yellowView.snp_top)
make.height.width.equalTo(yellowView)
}
NSLayoutAnchor写法
orangeView = UIView()
orangeView.backgroundColor = UIColor.orangeColor()
view.addSubview(orangeView)
orangeView.translatesAutoresizingMaskIntoConstraints = false
orangeView.topAnchor.constraintEqualToAnchor(yellowView.topAnchor, constant: 100).active = true
orangeView.leftAnchor.constraintEqualToAnchor(yellowView.leftAnchor).active = true
orangeView.widthAnchor.constraintEqualToAnchor(yellowView.widthAnchor, multiplier: 1, constant: 0).active = true
orangeView.heightAnchor.constraintEqualToAnchor(yellowView.heightAnchor, multiplier: 1, constant: 0).active = true
greenView = UIView()
greenView.backgroundColor = UIColor.greenColor()
view.addSubview(greenView)
greenView.translatesAutoresizingMaskIntoConstraints = false
greenView.topAnchor.constraintEqualToAnchor(orangeView.topAnchor).active = true
leftConstraint = greenView.leftAnchor.constraintEqualToAnchor(orangeView.rightAnchor, constant: 80)
leftConstraint?.active = true
greenView.heightAnchor.constraintEqualToAnchor(orangeView.heightAnchor).active = true
greenView.widthAnchor.constraintEqualToAnchor(orangeView.widthAnchor).active = true
动画的执行
override func viewDidLoad() {
super.viewDidLoad()
snpLayout()
anchorLayout()
let kissButton = UIButton(type: .System)
kissButton.setTitle("Kiss", forState: .Normal)
kissButton.addTarget(self, action: #selector(ViewController.kissButtonClick(_:)), forControlEvents: .TouchUpInside)
view.addSubview(kissButton)
kissButton.snp_makeConstraints { (make) in
make.bottom.equalTo(view).offset(-20)
make.centerX.equalTo(view)
make.width.equalTo(view).multipliedBy(0.8)
make.height.equalTo(60)
}
}
func kissButtonClick(sender: UIButton) {
UIView.animateWithDuration(1.5, delay: 0, options: [.Repeat, .CurveEaseInOut], animations: {
self.redView.snp_updateConstraints(closure: { (make) in
make.left.equalTo(self.yellowView.snp_right).offset(0)
})
self.leftConstraint?.constant = 0
self.view.layoutIfNeeded()
}, completion: nil)
}
效果图

网友评论