实施 UITabBarControllerDelegate 不起作用
Implementing UITabBarControllerDelegate does not work
我创建了一个新的 class 来实现 UITabBarControllerDelegate
,但是 class 中的方法没有被调用。
AppDelegate.swift:
func application() {
// ...
let controller = MyTabItemController()
let tabBarController = UITabBarController()
tabBarController.viewControllers = [controller]
tabBarController.delegate = MyTabBarControllerDelegate()
self.window?.rootViewController = tabBarController
// ...
}
MyTabBarControllerDelegate.swift:
class MyTabBarControllerDelegate: NSObject, UITabBarControllerDelegate{
func tabBarController(/*...*/) {
print("method invoked")
}
}
当我选择项目时,消息 "method invoked"
没有显示。
如果我让 AppDelegate
扩展 UITabBarControllerDelegate
,一切正常并且消息显示在控制台中。
我想知道为什么会这样?
UITabBarController
的delegate
属性弱。因此,您的委托在分配后直接被释放。您应该通过强引用来保留委托对象。
我创建了一个新的 class 来实现 UITabBarControllerDelegate
,但是 class 中的方法没有被调用。
AppDelegate.swift:
func application() {
// ...
let controller = MyTabItemController()
let tabBarController = UITabBarController()
tabBarController.viewControllers = [controller]
tabBarController.delegate = MyTabBarControllerDelegate()
self.window?.rootViewController = tabBarController
// ...
}
MyTabBarControllerDelegate.swift:
class MyTabBarControllerDelegate: NSObject, UITabBarControllerDelegate{
func tabBarController(/*...*/) {
print("method invoked")
}
}
当我选择项目时,消息 "method invoked"
没有显示。
如果我让 AppDelegate
扩展 UITabBarControllerDelegate
,一切正常并且消息显示在控制台中。
我想知道为什么会这样?
UITabBarController
的delegate
属性弱。因此,您的委托在分配后直接被释放。您应该通过强引用来保留委托对象。