iOS动画编程-AutoLayout动画[ 3 ] Animating by replacing constraints

288 查看

介绍

之前的几节中,我们都是通过修改一个约束的值来实现动画的。但是如果你想做的更多,你可能需要删除旧的约束并添加新的约束

删除约束

在IB中,我们可以为每一个约束注册一个identifier



在这个位置加入如下代码:

if constraint.identifier == "TitleCenterY" { constraint.active = false
//add new constraint
continue
}

如果你想移除这个约束,可以将它的active属性置为false
如果这时它没有其它引用,ARC机制将会将它回收

通过代码添加约束Adding constraints programmatically

在刚才代码的add new constraint位置加入:

let newConstraint = NSLayoutConstraint( item: titleLabel,
attribute: .CenterY,
relatedBy: .Equal,
toItem: titleLabel.superview!,
attribute: .CenterY,
multiplier: isMenuOpen ? 0.67 : 1.0, constant: 5.0)
newConstraint.identifier = "TitleCenterY"
newConstraint.active = true

这样我们就定义了一个新的约束,并使他生效
NSLayoutConstraint的构造器带有一大串的参数,不过幸好他们的排列方式正好如同一个方程

  • item: The first item in the equation, in this case the title label.

  • attribute: The attribute of the first item of the new constraint.

  • relatedBy: A constraint can represent either a mathematical equality or an inequality. In this book you’ll only use equality expressions, so here you use .Equal to represent this relationship.

  • toItem: The second item in the constraint equation; in this case, it’s your title’s superview.

  • attribute: The attribute of the second item of the new constraint. • multiplier: The equation multiplier as discussed earlier.

  • constant: The equation constant.
    随后的步骤中,我们为这个约束添加了一个identifier,并且使他生效
    *如果过去你就习惯于用代码添加约束,也许你会习惯于使用addConstraint方法,在iOS8+中,苹果推荐通过设置active属性使其生效

Adding menu content

actionToggleMenu方法底部加入如下的代码

if isMenuOpen {
        slider = HorizontalItemList(inView: view)
        slider.didSelectItem = { index in
        print("add \(index)")
        self.items.append(index)
        self.tableView.reloadData()
        self.actionToggleMenu(self)
        }
        self.titleLabel.superview!.addSubview(slider)
    }
    else {
    slider.removeFromSuperview()
    }

这样我们就加入了水平菜单