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

介绍

以前的几节中,咱们都是经过修改一个约束的值来实现动画的。可是若是你想作的更多,你可能须要删除旧的约束并添加新的约束express

删除约束

在IB中,咱们能够为每个约束注册一个identifier
图片描述
图片描述
图片描述
在这个位置加入以下代码:app

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

若是你想移除这个约束,能够将它的active属性置为false
若是这时它没有其它引用,ARC机制将会将它回收ide

经过代码添加约束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的构造器带有一大串的参数,不过幸亏他们的排列方式正好如同一个方程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属性使其生效

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()
    }

这样咱们就加入了水平菜单
图片描述

相关文章
相关标签/搜索