Search code examples
iosswiftuibuttonuitabbarcontrollersegue

Segue to a ViewController from a UIButton in Swift


I have a TabViewController that has three Tabs, which lead to a three ViewControllers.

I can segue just fine using the actual tab buttons of the TVC. However, I also want to segue to one of the tabs using a UIButton. I have a button in one ViewController and I want to segue to another, but not using the Tab Button.

I've had a couple of partial successes. By partial I mean the VC appears but the TabBar isn't present!

The code for the view controller where the UIButton is situated is below:

import UIKit

class HomeView: UIViewController {

    @IBOutlet var startBtn: UIButton! //Define the start button as a variable
    @IBOutlet var homeText: UILabel! //Define the text on the home screen

    override func viewDidLoad() {
        super.viewDidLoad()
        setBackground(); //Set background image
        setStartBtn();
        setHomeText();
    }

    func setBackground() {

        // Apply the insets…
        let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
        backgroundImage.image = UIImage(named: "Background.png")
        backgroundImage.contentMode = UIView.ContentMode.scaleAspectFill
        self.view.insertSubview(backgroundImage, at: 0)
    }

    func setStartBtn() {
        let startBtnText = NSLocalizedString("Start Test", comment: "")
        startBtn.addTarget(self, action: #selector(self.clickStart(_:)), for: .touchUpInside) //Add a target and action of the start buton
        startBtn.setTitle(startBtnText, for: [])
    }

    func setHomeText() {
        let homeTextStr = NSLocalizedString("Home Text", comment: "")
        homeText.text = homeTextStr
    }

    @objc func clickStart(_ sender: UIButton) {

    }
}

SOLUTION:

The Click Start function looks like this for what I need (thanks to the accepted answer below).

@objc func clickStart(_ sender: UIButton) {
    self.tabBarController?.selectedIndex = 1 // 1 is the second tab
}

This allowed me to move to the second tab bar item from a UIButton within the view


Solution

  • You need to embed each vc in the tab inside a navigationController , then use this to navigate to a nested vc

    @objc func clickStart(_ sender: UIButton) { 
       let vc = self.storyboard!.instantiateViewController(withIdentifier: "VCID") // set id for the destination vc
       self.navigationController?.pushViewController(vc,animated:true) 
    }
    

    And this to navigate to another vc inside the tab

    self.tabBarController?.selectedIndex = 1 // 1 is the second tab