使用自动布局开发,我们最好遵守下面的一些规定
所有使用约束设置位置的控件,不要再去设置frame
因为自动布局系统会根据设置的约束,自动的计算控件的frame
会在layoutSubviews函数中进行设置frame
如果我们去主动的修改了frame,会引起自动布局系统的计算错误
不要在layoutSubviews里面去修改约束,这样会出问题
所有使用约束设置位置的控件,不要再去设置frame
因为自动布局系统会根据设置的约束,自动的计算控件的frame
会在layoutSubviews函数中进行设置frame
如果我们去主动的修改了frame,会引起自动布局系统的计算错误
不要在layoutSubviews里面去修改约束,这样会出问题
自动布局的工作原理,有一个运行循环启动的时候,自动布局的系统就会去收集约束的变化
在运行循环结束之前,会去调用layoutSubviews函数就行统一的设置frame
如果我们想要某些约束提前进行更新,我们就可以使用layoutIfNeeded,去提前的更新这些约束
下面附上修改约束执行动画的代码
//设置动画效果,改变约束的位置,约束的修改是瞬时性的和frame不一样,所以放在动画中是无效的,修改frame是可动画属性
view.addConstraint(NSLayoutConstraint(item: iconView, attribute:.bottom, relatedBy: .equal, toItem: view, attribute: .bottom,
multiplier:1, constant: -view.bounds.size.height+200))
self.updateViewConstraints()
//设置WelcomeLabel的透明度为0
welcomeLabel.alpha = 0
UIView.animate(withDuration: 1.3, delay: 0, usingSpringWithDamping: 0.87, initialSpringVelocity: 11, options: [], animations: {
//有需要刷新的标记立刻调用layoutSubviews进行刷新
self.view.layoutIfNeeded()
}) { (_) in
UIView.animate(withDuration: 1.2, delay: 0, options: [], animations: {
//设置welecomeLabel的透明度为1
self.welcomeLabel.alpha = 1
}, completion: { (_) in
})
}