ios - 准备在 UITabbarController 中不调用 segue

标签 ios swift delegates uitabbarcontroller

我已经阅读了关于这个主题的所有其他帖子,但它们似乎对我没有帮助。

我有一个启动两个选项卡的 UITabBarController。我想将 tab1 中收集的数据传递给 UITabBar ViewController。我正在尝试为此使用 delegete 协议(protocol),但我无法在发送 ViewController 中设置委托(delegate)变量。永远不会调用 prepare for segue。我什至无法循环浏览 Tabbar Controller 的 ViewDidLoad() 内选项卡的 View Controller ,因为它们尚未创建,因此为零。

我以前使用过委托(delegate),它看起来相当简单。我在 Tabbar 中使用它重要吗?

当我运行代码时,会调用 TabBarViewController 中的 viewDidLoad() 但不会调用 preparefor segue。

调用了 MeViewController 中的 IBAction donePressed,但未调用委托(delegate),因为它未设置。

这是代码——

protocol DetailsDelegate: class {
    func myDetailsGathered( myDetails: MyDetails )
}

/// RECEIVING VIEW CONTROLLER

class TabBarViewController: UITabBarController, DetailsDelegate
{

    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        print("prepare for segue called\n");

        if let destinationViewController = segue.destination as? MeViewController
        {
            destinationViewController.delegate = self
        }

    }

    override func viewDidLoad()
    {
        print("ViewDidLoad Called \n")
    }

    func myDetailsGathered(myDetails: MyDetails)
    {
        self.myDetails = myDetails
        print("My details gathered \n")
    }

}

---------------
/// SENDING VIEW CONTROLLER

class MeViewController: UIViewController
{
    weak var delegate: DetailsDelegate?

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

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

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }

    // I have UIButton in the view and this is invoked when its pressed. 
    @IBAction func donePressed(_ sender: Any)
    {
        var infoToPass = MyDetails()

        print("looks like we are done")
        delegate?.myDetailsGathered(infoToPass: myDetails)
    }

}

最佳答案

prepareForSegue 在您执行转场时被调用。你不这样做,这就是它不会被调用的原因。

A segue defines a transition between two view controllers in your app’s storyboard file.

您应该使用单例 类来存储变量并在不同的 Controller 之间访问它们。你这样声明一个:

class Singleton {
    static let sharedInstance = Singleton()
    var name = ""
}

分配给单例:

Singleton.sharedInstance.name = "Some name"

从任何 Controller 读取它:

let name = Singleton.sharedInstance.name

关于ios - 准备在 UITabbarController 中不调用 segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46877330/

相关文章:

ios - 选择表情符号时键盘顶部出现随机蓝色

ios - SBJson iOS 解析器方法已弃用?

ios - if 语句后的预期声明

ios - 使用 AVPlayer 播放的视频从 swift3 的容器 View 中消失

c++ - 未解析的外部符号,带有自制委托(delegate)

ios - 设置文本字段的数值范围

swift - 快速创建FileAtPath

c# - 如何使用 Delegate.CreateDelegate 而不是 Func<> 定义委托(delegate)?

c# - 为什么不能直接在外部调用公共(public)事件?

ios - 分析 Xamarin.iOS 崩溃报告