如何用swift中的自定义视图以编程方式替换IBOutlet uiview

时间:2016-08-08 13:12:51

标签: ios swift uiview

在带有

的情节提要中,replacementViewUIView
@IBOutlet var replacementView: UIView!

连接。

我想用{/ 1>替换replacementView

replacementView = SecondViewController().view

但它不起作用。有什么问题?

2 个答案:

答案 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()
        }
    }
}