0

I'm adding a view to the window with this objective-c code:

  // Main Storyboard
  UIStoryboard *mainStoryBoard = [UIStoryboard  storyboardWithName:@"Main" bundle: nil];

  // View controller with the view to add
  UIViewController *vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"SomeViewController"];

  // Find the topmost window
  UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {
   return win1.windowLevel < win2.windowLevel || !win1.isOpaque;
  }] lastObject];

  // Add the view to the window
  [topWindow addSubview:vc.view];

This works fine and so does this Swift method I use in SomeViewController to leave the view:

// Get topmost window (Should be UIWindow)
let topWindow = UIApplication.shared.windows.sorted {
  (win1, win2) in
  return win1.windowLevel < win2.windowLevel || !win1.isOpaque
}.last

// Force view to prepare to disappear
self.viewWillDisappear(true)

// Send the view to the back
topWindow?.sendSubviewToBack(view)

This is the structure of my views after the objective-c code runs. The selected view is the one that got added:

Screenshot of view hierarchy

The issue is none of the buttons in the new view work so I can't trigger the above close method. I've tried both buttons added with the storyboard and programmatically added buttons. Visually the buttons react when tapped but they won't trigger anything.

iicaptain
  • 1,065
  • 1
  • 13
  • 37
  • 1
    All you are doing is adding a new ***view*** (which you pull from a storyboard designed view controller). The view controller likely is going out of scope and being removed, so the code is no longer available. You probably need to look at adding it as a `childController` or at least a persistent var / property. – DonMag Feb 11 '20 at 13:29
  • @DonMag That would make sense except the rest of the code in the view controller is still functioning normally. All the code in viewDidLoad executes etc. – iicaptain Feb 11 '20 at 13:32
  • 1
    Yes... all the code executes *while the VC exists*. Assuming the code you show above is in a method, as soon as the method exits the VC no longer exists - you've added it's view to the view hierarchy, but the class itself goes out of scope. – DonMag Feb 11 '20 at 13:39

1 Answers1

0

I ended up resolving the issue by completely swapping out the root view controller rather than simply adding it's view as a subview. The problem was as @DonMag pointed out that I was adding the subview without it's view controller. I found this question about swapping the root view controller and used that as a basis for my changes. If someone wants to provide a complete solution that doesn't require swapping the root view controller I'll accept that instead.

iicaptain
  • 1,065
  • 1
  • 13
  • 37