[英]Why can't I set a view from a different ViewController view?
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let storyboard = UIStoryboard(name: "LinkDetail", bundle: nil)
var vc : UIViewController = storyboard.instantiateViewControllerWithIdentifier("red") as UIViewController
containerView = vc.view
println(vc.view)
}
I know I have the view controller id set in storyboard to be "red". 我知道我在故事板中设置的视图控制器ID为“红色”。 And when I println the output is:
当我打印输出时:
<UIView: 0x7fbdc1e5a820; frame = (0 0; 375 667); autoresize = W+H; layer = <CALayer: 0x7fbdc1e491b0>>
so the view must have been gotten correctly. 所以视图必须正确。 So why can't I swap out my containerView UIView outlet with the view I get from code?
那么为什么我不能用我从代码中获得的视图换出我的containerView UIView插座?
This is because you aren't holding a reference to the vc
(red) view controller anywhere. 这是因为您没有在任何地方保持对
vc
(红色)视图控制器的引用。 The containerView
is set to weak so nothing will retain the view that's being set on it. containerView
设置为weak,因此不会保留正在其上设置的视图。
I think you should be using Child View Controllers in this case. 我想你应该在这种情况下使用子视图控制器 。
Using your snippet, this is how you would add the View Controller as a child: 使用您的代码段,您可以将View Controller添加为子项:
override func viewDidLoad() {
super.viewDidLoad()
let storyboard = UIStoryboard(name: "LinkDetail", bundle: nil)
var vc : UIViewController = storyboard.instantiateViewControllerWithIdentifier("red") as UIViewController
self.addChildViewController(vc)
self.view.addSubview(vc.view)
containerView = vc.view
vc.didMoveToParentViewController(self)
}
// containerView = vc.view
containerView.addSuvview(vc.view)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.