caxix caxix - 1 year ago 77
Swift Question

Detached Controller Issues on a Dynamically Loaded UIStackView

I am getting a "Presenting view controllers on detached view controllers is discouraged" warning in a somewhat specialized architecture. And - there are some fairly big UI issues resulting from it. I have an architecture with 2 distinct unconnected groups in my storyboard. The first group is the main interface of my app and includes an UIStackView. The second group consists of an UIView plus attached popover segue as shown in the image below.

enter image description here

I dynamically populate the UIStackView of group 1 with up to 8 instances of the UIView of group 2. This is done in a function called loadViews() in the UIStackView subclass which is called as needed. Here is the cleaned up pseudo code for illustration:

for i in 0 ..< green.count {

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let greenVC = storyboard.instantiateViewControllerWithIdentifier("greenViewController") as! GreenVC
greenVC.progressionStackView = self
greenVC.index = i;


if let greenView = greenVC.view as! GreenView! {
greenView.fillColor = UIColor.orangeColor()


Every time I trigger the popover on one of the embedded green views in the stack view I get the warning from above. More importantly, when running on an iPad in split view mode, the stack view loses a green view each time until there are none left. The latter is just a display issue, because on refresh all views are back.

I am completely stumped and am not sure how to fix this or implement things differently. If the issue is that the loaded views are not attached, can they be "re-attached"? Or is there a way to dynamically load a stack view with up to 256 views that are attached to it?

Answer Source


Another lesson in taking Xcode warnings to heart - even if the word discouraged is used. As in this case, things tend to break. The solution was obvious in hindsight. The new view controllers that were instantiated as greenVC had to be attached to the containing view controller - i.e. the one several layers up in the view hierarchy that contains this UIStackView:


The line above is called right before appending greenVC to my array of added view controllers. Of course now removeFromParentViewController() has to be called as well where instances of GreenVC get removed, but otherwise that's it. The warning is gone and so is the issue of vanishing views.