ios - 为什么我设置后 UITabBarControllerDelegate 就为零?

标签 ios swift delegates uitabbarcontroller

我有一个涉及 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)")
    }

}

然后,在我的 Storyboard 中,我有一个普通的 UITabBarController,它连接了两个普通的 UIViewControllers。我只是想捕获选项卡更改事件,但由于某种原因,我的 MainTabBarControllerdelegate 未正确设置。

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

did set delegate to nil

为什么它不创建 MainTabBarControllerDelegate 的正确实例以便可以调用其委托(delegate)方法?

最佳答案

在这里self.delegate = MainTabBarControllerDelegate()您创建了一个委托(delegate)并立即将其分配给delegate属性,该属性是weak。因此,委托(delegate)被创建,但随后立即被处置,因为没有任何东西对其具有强引用。

关于ios - 为什么我设置后 UITabBarControllerDelegate 就为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34608397/

相关文章:

objective-c - 使用 XIB 在 View Controller 上以编程方式初始化 UISegmentedControl

swift - Linux 导出路径错误替换

c# - 有没有办法直接使用 C# 方法作为委托(delegate)?

ios - 即使设置了更高的 gps 精度 (kCLLocationAccuracyThreeKilometers),位置也会更新

objective-c - 带有不突出显示的渐变层的 UIButton

swift - 我的自定义相机 View 有什么问题?

ios - 我的应用程序因 'Could not cast value of type x to ' UITableViewdelegate' 而崩溃

c# - 我使用委托(delegate)还是事件

iphone - 如何在我的 iPhone 应用程序中制作欢迎屏幕?

ios - 应用被杀死时如何判断应用是从NotificationCenter(Local Notification)打开还是从应用图标打开