2

使用 MDCTabBarViewController 选择标签栏项目时收到错误:“由于未捕获的异常 'NSInvalidArgumentException',原因:'Invalid item',正在终止应用程序”。视图控制器加载但在选择第二个选项卡后立即崩溃。

    class BusTabBarController: MDCTabBarViewController {

        override func viewDidLoad() {
            super.viewDidLoad()

            view.backgroundColor = .white
            loadTabBar()
        }

        func loadTabBar() {

            let firstVC = BusStopFlexibleHeaderContainerViewController()
            let secondVC = BookmarksFlexibleHeaderContainerViewController()
            let thirdVC = UIViewController()

            let viewControllersArray = [firstVC, secondVC, thirdVC]
            viewControllers = viewControllersArray

            let childVC = viewControllers.first
            selectedViewController = childVC

            tabBar?.delegate = self

            tabBar?.items = [UITabBarItem(title: "Recents", image: nil, tag: 0),
                         UITabBarItem(title: "Favorites", image: nil, tag: 0),                                                           
                         UITabBarItem(title: "YAY", image: nil, tag: 2)]

            tabBar?.selectedItem = tabBar?.items.first

            tabBar?.backgroundColor = MDCPalette.grey.tint900
            tabBar?.selectedItemTintColor = .white
            tabBar?.unselectedItemTintColor = MDCPalette.grey.tint400
            tabBar?.inkColor = MDCPalette.blueGrey.tint100

        }

任何帮助表示赞赏。谢谢!

4

1 回答 1

1

我也有同样的问题。在执行MDCTabBarViewController的时候

-(void)setSelectedViewController:(nullable UIViewController *)selectedViewController 

被解雇有一行代码:

self.tabBar.selectedItem = selectedViewController.tabBarItem;

因此,如果您不将 barItem 设置为控制器,您将收到该错误,因为引用为 nil

我更新了你的代码,所以我希望这能解决你的问题(我安装了 pod 版本 26)

class BusTabBarController: MDCTabBarViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = .white
    loadTabBar()
}

func loadTabBar() {

    let firstVC = BusStopFlexibleHeaderContainerViewController()
    firstVC.tabBarItem = UITabBarItem(title: "Recents", image: nil, tag: 0)

    let secondVC = BookmarksFlexibleHeaderContainerViewController()
    secondVC.tabBarItem =  UITabBarItem(title: "Favorites", image: nil, tag: 0)

    let thirdVC = UIViewController()
    thirdVC.tabBarItem = UITabBarItem(title: "YAY", image: nil, tag: 2)

    let viewControllersArray = [firstVC, secondVC, thirdVC]
    viewControllers = viewControllersArray

    let childVC = viewControllers.first
    selectedViewController = childVC

    tabBar?.delegate = self

    tabBar?.items = [firstVC.tabBarItem,
                     secondVC.tabBarItem ,
                     thirdVC.tabBarItem]

    tabBar?.selectedItem = tabBar?.items.first

    tabBar?.backgroundColor = MDCPalette.grey.tint900
    tabBar?.selectedItemTintColor = .white
    tabBar?.unselectedItemTintColor = MDCPalette.grey.tint400
    tabBar?.inkColor = MDCPalette.blueGrey.tint100

}
}
于 2017-09-06T14:06:58.230 回答