这就是我解决这个问题的方法,UIScrollView 中的views 之一就是我所说的containerView,例如,我的ViewController 中有containerView 的出口。这是我的层次结构在测试应用程序中的样子:
如您所见,我目前在 containerView 中有一个子视图,它定义了一个高度,橙色的 BottomView - 具有为 containerView 定义的垂直间距约束。
当用户点击替换视图(在我的示例中为replaceView(_) 方法)时,您只需首先从containerView 中删除所有子视图,然后添加新视图,因为我们使用自动布局,橙色视图将始终位于下方容器视图无论容器视图有多大/多小...
@IBAction func replaceView(_ sender: UIButton) {
//remove all subviews from container view to be replaced
for subview in containerView.subviews {
subview.removeFromSuperview()
}
let greenView = UIView()
greenView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(greenView)
NSLayoutConstraint.activate([
greenView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
greenView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
greenView.topAnchor.constraint(equalTo: containerView.topAnchor),
greenView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
greenView.heightAnchor.constraint(equalToConstant: 50)
])
greenView.backgroundColor = .green
}
如果您想在另一个 Storyboard View Controller 中添加一个视图,您可以像这样添加它:
我假设您的 Storyboard 被称为 Main 并且我添加的视图控制器的 Storyboard ID 是 GreenStoryboardID
@IBAction func replaceView(_ sender: UIButton) {
//remove all subviews from container view to be replaced
for subview in containerView.subviews {
subview.removeFromSuperview()
}
let storyboard = UIStoryboard(name: "Main", bundle:nil)
let greenViewController = storyboard.instantiateViewController(withIdentifier: "GreenStoryboardID")
guard let greenView = greenViewController.view else { fatalError() }
//add view properly so it is uses UIViewController contaniment methods
addChildViewController(greenViewController)
containerView.addSubview(greenView)
greenViewController.didMove(toParentViewController: self)
greenView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
greenView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
greenView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
greenView.topAnchor.constraint(equalTo: containerView.topAnchor),
greenView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
greenView.heightAnchor.constraint(equalToConstant: 50)
])
}
这取决于你如何正确调整视图控制器的大小,这里我只是将它的高度设置为 50,但是你可以在 UIViewController 子类中有一个方法,例如它可以让你知道有多大视图必须适合所有内容到容器视图中