我想我找到了一个固定电话
self.view.layoutIfNeeded()
在
animations
块
import UIKit
class ViewController: UIViewController {
var showB = true
weak var viewB: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let viewA = UIView()
viewA.backgroundColor = UIColor.green
let toggleViewBButtonAnimated = UIButton(frame: CGRect(x: 50, y: 150, width: 200, height: 40))
toggleViewBButtonAnimated.backgroundColor = UIColor.cyan
toggleViewBButtonAnimated.setTitle("Toggle B (animated)", for: .normal)
viewA.addSubview(toggleViewBButtonAnimated)
toggleViewBButtonAnimated.addTarget(self, action: #selector(toggleBButtonTappedAnimated), for: .touchUpInside)
let viewB = UIView()
viewB.backgroundColor = UIColor.orange
let viewBHeightConstraint = viewB.heightAnchor.constraint(equalToConstant: 200)
viewBHeightConstraint.priority = 999
viewBHeightConstraint.isActive = true
self.viewB = viewB
let stackView = UIStackView(arrangedSubviews: [viewA, viewB])
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(stackView)
stackView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
}
@IBAction func toggleBButtonTappedAnimated() {
self.showB = !self.showB
UIView.animate(withDuration: 0.3,
animations: { self.viewB.isHidden = !self.showB; self.view.layoutIfNeeded() }
)
}
}
该控制器设置
UIStackView
它有两个垂直视图,一个绿色的(a)和一个橙色的(B)。点击按钮隐藏/取消隐藏视图B。
不
有
动画
然后,当显示视图B时,它会从屏幕顶部飞入。(当视图B被隐藏时,它会正常隐藏-从屏幕底部向下移动。)
到
块,视图B按预期显示-它从屏幕底部出现。
感谢@g3rv4的回答,为我指明了这个方向!