以前的幾節中,咱們都是經過修改一個約束的值來實現動畫的。可是若是你想作的更多,你可能須要刪除舊的約束並添加新的約束express
在IB中,咱們能夠爲每個約束註冊一個identifier
在這個位置加入以下代碼:app
if constraint.identifier == "TitleCenterY" { constraint.active = false //add new constraint continue }
若是你想移除這個約束,能夠將它的active屬性置爲false
若是這時它沒有其它引用,ARC機制將會將它回收ide
在剛纔代碼的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的構造器帶有一大串的參數,不過幸虧他們的排列方式正好如同一個方程this
item: The first item in the equation, in this case the title label.spa
attribute: The attribute of the first item of the new constraint.code
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.ip
attribute: The attribute of the second item of the new constraint. • multiplier: The equation multiplier as discussed earlier.rem
constant: The equation constant.
隨後的步驟中,咱們爲這個約束添加了一個identifier,而且使他生效
*若是過去你就習慣於用代碼添加約束,也許你會習慣於使用addConstraint方法,在iOS8+中,蘋果推薦經過設置active屬性使其生效
在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() }
這樣咱們就加入了水平菜單