也许你在写OC的时候已经用过了Masonry
这个第三方库来写自动布局,今天我们来说说Swift版本的Masonry
第三方库SnapKit
snp_remakeConstraints
snp_remakeConstraints
is similar tosnp_makeConstraints
, but will first remove all existing constraints installed by SnapKit.
移除之前的所有约束,然后添加新约束的方法是:snp_makeConstraints
snp_makeConstraints
这个方法。 效果图:
Show Your Code
初始化 button
var button: UIButton! var isExpanded = false button = UIButton(type: UIButtonType.System) button.setTitle("点击展开", forState: .Normal) button.layer.borderWidth = 3 button.layer.borderColor = UIColor.redColor().CGColor button.backgroundColor = UIColor.greenColor() button.addTarget(self, action: "change", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(button)
重写方法
override func updateViewConstraints() {// 这里使用update也是一样的。// remake会将之前的全部移除,然后重新添加 button.snp_remakeConstraints { (make) -> Void in make.top.leading.trailing.equalTo(view) if isExpanded { make.bottom.equalTo(view) }else { make.bottom.equalTo(-300) } } super.updateViewConstraints() }
按钮方法
func change() { isExpanded = !isExpanded if !isExpanded { button.setTitle("点击展开", forState: .Normal) }else { button.setTitle("点击收起", forState: .Normal) } self.view.setNeedsUpdateConstraints() self.view.updateConstraintsIfNeeded() UIView.animateWithDuration(0.5) { () -> Void in self.view.layoutIfNeeded() } }