【问题标题】:'UITabBarDelegate' cannot be constructed because it has no accessible initializers'UITabBarDelegate' 无法构造,因为它没有可访问的初始化程序
【发布时间】:2015-03-11 00:58:25
【问题描述】:

我从 Android 开发背景进入 iOS 世界。

我试图避免那些将情节提要项目直接连接到我的控制器(如@IBOutlet)的奇怪模式(至少对于 Android 开发人员而言)。

我想知道是否可以创建一个匿名函数来委托 UITabBar 的某些事件:

    let tabBarDelegate = UITabBarDelegate {
        func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
            label.text = item.title
        }
    }

    tabBar.delegate = tabBarDelegate

我面临的错误是:'UITabBarDelegate' cannot be constructed because it has no accessible initializers

我对这个世界真的很陌生。我怎样才能做到这一点?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您不能实例化 UITabBarDelegate,因为它是一个协议(类似于 Java 中的接口),而不是一个类。

    你必须让你的一个类声明它实现了 UITabBarDelegate,然后将该类的一个实例设置为标签栏的委托。

    这是一个简短的例子:

    class MyViewController: UIViewController, UITabBarDelegate {
        //all of UITabBarDelegate's methods are optional, so you don't have to implement them
        func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
        }
    }
    
    var viewController = MyViewController()
    var tabBar = UITabBar()
    tabBar.delegate = viewController
    

    另外,我不相信你可以在 Swift 中创建匿名类。

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 2018-09-30
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      相关资源
      最近更新 更多