在带有
的情节提要中,replacementView
为UIView
@IBOutlet var replacementView: UIView!
连接。
我想用{/ 1>替换replacementView
replacementView = SecondViewController().view
但它不起作用。有什么问题?
答案 0 :(得分:1)
replacementView
仅供参考。您必须在视图堆栈中更改对象。
您应该继续引用replacementView
的父母。接下来从parentView中删除replacementView
并将SecondViewController().view
添加到parentView。
我建议您尝试将SecondViewController().view
添加为replacementView
并添加填充限制。
你还应该记住保留SecondViewController,否则它可能会在它出现之前被处理。阅读addChildViewController(childController: UIViewController)
UIViewController方法。
答案 1 :(得分:-1)
本质上,您需要向要添加的视图添加约束,然后删除旧视图。假设项目在您的父视图中按顺序排列,这里有一些代码可以为您执行此操作。
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()
}
}
}