Search code examples
iosswiftxcodetabbarcontroller

How to perform show segue from tab bar controller?


I have a tab bar controller with 2 views attached, each embed in navigation controller. I've made a segue kind show from tab bar controller to another view controller with identifier "toNew". In one of the tab bar views I have a button which should trigger this segue with identifier "toNew". I tried DataDelegate but it doesn't work here.

It's this part of storyboard

This is view controller file for view controller attached in tab bar

import UIKit

protocol DataDelegate {
func sendData(data : String)
}

class NavContToNew: UIViewController , UITabBarDelegate {

var delegate : DataDelegate?
var data : String = "ToNew"

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func dismiss(_ sender: Any) {
    //self.dismiss(animated: true, completion: nil)
    self.delegate?.sendData(data:self.data)
    print("Perform segue delegate")
}
}

And this is tab bar controller.swift file

import UIKit

class TabBarCont: UITabBarController , DataDelegate {


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func sendData(data: String) {
    if data == "ToNew" {
        print("Segue perform")
        self.performSegue(withIdentifier: "toNew", sender: self)
    }
}
}

Solution

  • In you NavContToNew , you haven't assigned a delegate.

    @IBAction func dismiss(_ sender: Any) {
                self.delegate = self.tabBarController as! TabBarCont
        //self.dismiss(animated: true, completion: nil)
        self.delegate?.sendData(data:self.data)
        print("Perform segue delegate")
    }
    

    By the way , you don't need to use delegate. You can call your taBarController anywhere in its viewControllers. Here, you can call it in NavContToNew without using delegate.

    self.tabBarController?.performSegue(withIdentifier: "toNew", sender: self.tabBarController)