在Storyboard中,它将一个名为replacementView
的视图替换为UIView
。
@IBOutlet var replacementView: UIView!
已连接。
我想用另一个视图替换replacementView
。
replacementView = SecondViewController().view
但是它不起作用。问题出在哪里?
replacementView
只是一个引用。你需要改变视图堆栈中的对象。
你应该保留对replacementView
的父级的引用。接下来,从parentView中删除replacementView
,并将SecondViewController().view
添加到parentView中。
我建议您尝试将您的SecondViewController().view
作为replacementView
添加,并添加填充约束。
您还应该记住保留SecondViewController
,否则它可能在出现之前被释放。请阅读有关addChildViewController(childController: UIViewController)
UIViewController方法的内容。
基本上,您需要向要添加的视图添加约束,然后删除旧视图。假设项目在父视图中按顺序排列,以下是一些可以为您执行此操作的代码。
func replaceView(oldView:UIView, newView: UIView, spacingBetweenViews: CGFloat) {
//loop through, find the view, and add a constraint between the next and previous items.
let parentView = oldView.superview ?? UIView()
for (index, subview) in parentView.subviews.enumerated() {
let PREVIOUS_VIEW = index - 1
let NEXT_VIEW = index + 1
if subview == oldView {
if index == 0 {
//if the first view
let constraints = [
parentView.topAnchor.constraint(
equalTo: newView.topAnchor,
constant: spacingBetweenViews),
newView.bottomAnchor.constraint(
equalTo: parentView.subviews[NEXT_VIEW].topAnchor,
constant: spacingBetweenViews)
]
NSLayoutConstraint.activate(constraints)
} else if index == parentView.subviews.count - 1 {
// if the last view
let constraints = [
parentView.subviews[PREVIOUS_VIEW].bottomAnchor.constraint(
equalTo: newView.topAnchor,
constant: spacingBetweenViews),
newView.bottomAnchor.constraint(
equalTo: parentView.bottomAnchor,
constant: spacingBetweenViews)
]
NSLayoutConstraint.activate(constraints)
} else {
let constraints = [
parentView.subviews[PREVIOUS_VIEW].bottomAnchor.constraint(
equalTo: newView.topAnchor,
constant: spacingBetweenViews),
newView.bottomAnchor.constraint(
equalTo: parentView.subviews[NEXT_VIEW].topAnchor,
constant: spacingBetweenViews)
]
NSLayoutConstraint.activate(constraints)
}
parentView.subviews[index].removeFromSuperview()
}
}
}
addSubView:
方法。 - Midhun MP