简体   繁体   中英

'UITabBarDelegate' cannot be constructed because it has no accessible initializers

I came from a background in Android development to the iOS world.

I'm trying to avoid those odd patterns (at least for a Android dev) that connects storyboard items directly to my controller (like @IBOutlet).

I want to know if it's possible to create an anonymous function to delegate some events of a UITabBar:

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

    tabBar.delegate = tabBarDelegate

The error I'm facing is this one: 'UITabBarDelegate' cannot be constructed because it has no accessible initializers .

I'm really new to this world. How can i accomplish that?

You can't instantiate a UITabBarDelegate because it is a protocol (similar to an interface in Java), not a class.

You have to have one of your classes declare that it implements UITabBarDelegate, then set an instance of that class as the tab bar's delegate.

Here's a short example:

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

Also, I don't believe you can create anonymous classes in Swift.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM