如何从标签栏控制器执行show segue?

时间:2018-09-21 21:53:27

标签: ios swift xcode tabbarcontroller

我有一个带有2个视图的标签栏控制器,每个视图都嵌入在导航控制器中。我从标签栏控制器到另一个标识符为“ toNew”的视图控制器进行了segue种显示。在一个标签栏视图中,我有一个按钮,该按钮应使用标识符“ toNew”触发此segue。 我尝试了DataDelegate,但在这里不起作用。

It's this part of storyboard

这是附加在标签栏中的用于视图控制器的视图控制器文件

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")
}
}

这是标签栏controller.swift文件

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)
    }
}
}

1 个答案:

答案 0 :(得分:0)

在NavContToNew中,您尚未分配代理。

@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")
}

顺便说一句,您不需要使用委托。您可以在其viewControllers中的任何位置调用taBarController。在这里,你可以叫它 NavContToNew,无需使用委托。

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