-1

At the very bottom is my code where MainController initiates a subview called setController. However, within setController's code I get back a nil when I try to the superview:

override func viewDidLoad() {
    super.viewDidLoad()
    print(self.view.superview ?? "no parent")
}

I am assigning the second view as a subview, but obviously I am missing something. Have I misunderstood how UIView hierarchy works?

class MainController: UIViewController {
    
    private lazy var setController = SetController()
    var invButton   : MyButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        invButton = makeButton(vControl: self, btype: ButtType.inv, action: #selector(self.buttonAction(sender:)))
        invButton.frame.origin.x = self.view.frame.width * 0.1
        invButton.frame.origin.y = self.view.frame.height * 0.1
        invButton.setTitle("Settings", for: .normal)
    }

    override var prefersStatusBarHidden: Bool {
        return false
    }
    
    @objc func buttonAction(sender: UIButton!) {
        guard let theButton = sender as? MyButton else { return}

        UIView.transition(with: self.view, duration: 0.5, options: .transitionCurlDown, animations: { [self] in
          self.view.addSubview(setController.view)
        }, completion: nil)
    }
}
Yrb
  • 8,103
  • 2
  • 14
  • 44
LuisC329
  • 131
  • 8
  • Does this answer your question? [Adding a view controller as a subview in another view controller](https://stackoverflow.com/questions/27276561/adding-a-view-controller-as-a-subview-in-another-view-controller). You probably need to call `addChild` and `didMove(toParent:)` on your `setController` – Andrew Dec 02 '21 at 22:24
  • 1
    This isn’t SwiftUI – lorem ipsum Dec 02 '21 at 23:10

1 Answers1

-1

For anyone coming across this problem as well, I found the answer here:

https://guides.codepath.com/ios/Adding-and-Removing-Child-View-Controllers

The error was mine in that I didn't realize that adding a subview was a multiple line process.

So self.view.addSubview(setController.view) became:

addChild(setController);
view.addSubview(setController.view);
setController.didMove(toParent: self);
LuisC329
  • 131
  • 8