2017-06-21 56 views
2

好吧,我刚刚遇到了奇怪的事情。我有我的应用程序控制器依赖注入视图(标题)到视图控制器。该视图控制器以模态方式呈现另一个视图控制器,并且依赖注入它自己的头以供呈现视图控制器使用。但是,当它从第一个控制器提交标题消失。为什么在呈现视图控制器后UIView从图层中删除?

属性仍然设置,但它已从视图层次结构中删除。

class ViewController: UIViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.view.backgroundColor = .white 

     let button = UIButton(frame: CGRect(x: 0, y: 20, width: 100, height: 50)) 
     button.setTitle("Click Me!", for: .normal) 
     button.addTarget(self, action: #selector(self.segue), for: .touchUpInside) 
     button.backgroundColor = .black 
     button.setTitleColor(.lightGray, for: .normal) 

     self.view.addSubview(button) 
    } 

    func segue() { 
     let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) 
     view.backgroundColor = .lightGray 

     let firstVC = FirstViewController() 
     firstVC.sharedView = view 

     present(firstVC, animated: false) 
    } 
} 

class FirstViewController: UIViewController { 
    var sharedView: UIView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.view.backgroundColor = .white 

     self.view.addSubview(self.sharedView) 

     let button = UIButton(frame: CGRect(x: 0, y: 200, width: 100, height: 50)) 
     button.setTitle("Click Me!", for: .normal) 
     button.addTarget(self, action: #selector(self.segue), for: .touchUpInside) 
     button.backgroundColor = .black 
     button.setTitleColor(.lightGray, for: .normal) 

     self.view.addSubview(button) 
    } 

    func segue() { 
     let secondVC = SecondViewController() 
     secondVC.sharedView = self.sharedView 

     present(secondVC, animated: true) 
    } 
} 

class SecondViewController: UIViewController { 
    var sharedView: UIView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.view.backgroundColor = .white 

     self.view.addSubview(self.sharedView) 

     let button = UIButton(frame: CGRect(x: 0, y: 200, width: 100, height: 50)) 
     button.setTitle("Click Me!", for: .normal) 
     button.addTarget(self, action: #selector(self.segue), for: .touchUpInside) 
     button.backgroundColor = .black 
     button.setTitleColor(.lightGray, for: .normal) 

     self.view.addSubview(button) 
    } 

    func segue() { 
     self.dismiss(animated: true) 
    } 
} 

有人能解释什么是怎么回事:

我在新鲜singleview项目重现这个问题?为什么sharedView从FirstViewController中消失?

+2

在'addSubview()'的文档中:'Views只能有一个超级视图。如果视图已经有一个超级视图,并且该视图不是接收者,那么在使接收者成为新的超级视图之前,此方法将删除先前的超级视图。“我认为这是问题所在。你可能想要这个:https://stackoverflow.com/questions/4425939/can-uiview-be-copied – Larme

+0

啊,这是有道理的。任何建议,使其正常工作? –

+0

我编辑了我以前的评论与可能的解决方案。但是我会使用一种方法来创建该头部视图并进行所有自定义并调用它。 – Larme

回答

1

截至-addSubview(_:)商务部:

视图只能有一个上海华。如果视图已经有一个超级视图,并且该视图不是接收者,则在使接收者成为新的超级视图之前,此方法将删除以前的超级视图。

这应该解释你的问题。

我建议您改为创建一个方法,根据您的自定义风格生成headerView(每次都有一个新的)。

如果您真的想“复制”该视图,可以查看that answer。由于UIViewNSCopying标准,他们的诀窍是“存档/编码”它,因为它是NSCoding兼容,复制归档和“取消存档/解码”它的副本。

相关问题