当咱们使用 frame 布局控件的时候,若是控件的 frame 发生改变时,咱们想让改变产生动画过渡效果,而不是生硬的直接改变。咱们可使用 UIView 的 animate(withDuration:animations:completion:)
函数来实现,以下面的代码:bash
UIView.animate(withDuration: 0.5) {
// 改变后的frame
self.exampleView.frame = CGRect(x: 10, y: 10, width: 100, height: 100)
}
复制代码
那当咱们使用 AutoLayout 布局的时候,咱们想实现上面的效果该如何写呢?ide
经过下面的两个步骤咱们就能够实现:函数
animate(withDuration:animations:completion:)
函数
layoutIfNeeded()
函数private let exampleView = UIView(frame: .zero)
private var topConstraint = NSLayoutConstraint()
复制代码
extension ViewController {
private func setupSubviews() {
exampleView.backgroundColor = .green
view.addSubview(exampleView)
exampleView.translatesAutoresizingMaskIntoConstraints = false
topConstraint = exampleView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100)
topConstraint.constant = 100
NSLayoutConstraint.activate([
topConstraint,
exampleView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 100),
exampleView.widthAnchor.constraint(equalToConstant: 100),
exampleView.heightAnchor.constraint(equalToConstant: 100)
])
let button = UIButton(type: .custom)
button.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
button.backgroundColor = .red
button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
view.addSubview(button)
}
}
复制代码
extension ViewController {
@objc func buttonAction(_ sender: UIButton) {
// 修改约束
topConstraint.constant = 200
//调用父视图的 layoutIfNeeded()
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
}
}
复制代码
父视图
的 layoutIfNeeded()
函数layoutIfNeeded()
函数,不是 setNeedsLayout()