Search code examples
iosswiftuinavigationcontrolleruibuttonuitabbarcontroller

How to push a ViewController from a UIButton that is embedded in Tab Bar Controller


In want to have a button floating next to my Tab Bar. When pressed, this button will open a View that can be Navigated (so a View Controller embedded in a Navigation Controller(?)).

In UITabBarController {

ViewDidLoad() {
super.viewDidLoad()

//I have my 5 tab bar items set up programatically here.  
//The middle tab bar item is disabled because the button is on top of it

setupMiddleButton()

}

My setupMiddleButton function

let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 52, height: 52))
//..various styling and alignment values...
view.addSubview(menuButton)
menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)

finally I've tried to add the code to push the view controller, however I receive nil when tapping the button.

@objc private func menuButtonAction(sender: UIButton) {
                
let createController = CreateViewController()
let nav3 = UINavigationController(rootViewController: createController)
            
nav3.navigationController!.pushViewController(createController, animated: true)


Solution

  • So I figured it out. Turns out it was much simpler than I thought, which makes me think I was explaining myself poorly in the question. Anyway, here's the code that worked for me.

    let myViewController = ViewController()
    let nav = UINavigationController(rootViewController: myViewController)
    
    self.present(nav, animated:true, completion: nil)