为什么UITabBarControllerDelegate在我设置好之后呢? [英] Why is the UITabBarControllerDelegate nil right after I set it?

查看:201
本文介绍了为什么UITabBarControllerDelegate在我设置好之后呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题涉及 UITabBarControllerDelegate

I have a weird issue involving UITabBarControllerDelegate.

我使用以下代码:

import UIKit

class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = MainTabBarControllerDelegate()
        print("did set delegate to \(self.delegate)")
    }

}

class MainTabBarControllerDelegate: NSObject, UITabBarControllerDelegate {

    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
        print("selected: \(viewController) --> index: \(tabBarController.selectedIndex)")
    }

}

然后,在我的故事板中,我有两个简单的 UIViewControllers 的vanilla UITabBarController >连接到它。我只是想抓住标签更改事件,但由于某种原因,我的 MainTabBarController 中的委托未设置

Then, in my Storyboard I have the vanilla UITabBarController with two plain UIViewControllers connected to it. I simply want to catch the tab change events, but for some reason the delegate of my MainTabBarController doesn't get set properly.

当我使用上面的代码运行项目时,控制台输出:

When I run the project with the code from above, the console outputs:

did set delegate to nil

为什么不创建一个正确的 MainTabBarControllerDelegate ,以便其委托方法可以调用?

Why doesn't it create a proper instance of MainTabBarControllerDelegate so that its delegate methods can be called?

推荐答案

code> self.delegate = MainTabBarControllerDelegate()您创建一个委托,并立即将其分配给委托属性,这是 weak 。所以代表得到创建,但是立即处理,因为没有什么可以强加它的参考。

Here self.delegate = MainTabBarControllerDelegate() you create a delegate and immediately assign it to the delegate property, which is weak. So the delegate gets created but then immediately disposed because there is nothing that holds a strong reference to it.

这篇关于为什么UITabBarControllerDelegate在我设置好之后呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆