将UITabBarItem添加到现有的UITabBar(在故事板中制作)

时间:2015-03-19 20:36:43

标签: xcode swift storyboard uitabbarcontroller

因此,我需要在故事板中创建的现有UITabBarItem中添加新的UITabBar

到目前为止,我认为我已经能够正确访问UITabBar,但无法创建UITabBarItem并将其添加到UITabBar

到目前为止,我已经得到了:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    var tabBarController = self.window!.rootViewController as UITabBarController
    var tabBar = tabBarController.tabBar as UITabBar

    var tabBarItem1 = tabBar.items![0] as UITabBarItem
    var tabBarItem2 = tabBar.items![1] as UITabBarItem
    var tabBarItem3 = tabBar.items![2] as UITabBarItem

    tabBarItem1.selectedImage = UIImage(named: "tab-frame-on")
    tabBarItem2.selectedImage = UIImage(named: "tab-quote-on")
    tabBarItem3.selectedImage = UIImage(named: "tab-hash-on")

    var instaTab: UITabBarItem = UITabBarItem(title: "", image: UIImage(named: "tab-instagram-off"), selectedImage: UIImage(named: "tab-instagram-on"))
    tabBar.items?.append(instaTab)

    return true

}

此功能是AppDelegate的一部分。您可以在第14行看到我正在创建UITabBarItem,如此:var instaTab: UITabBarItem = UITabBarItem(title: "", image: UIImage(named: "tab-instagram-off"), selectedImage: UIImage(named: "tab-instagram-on")),然后尝试通过附加它将其添加到现有的tabbar项目中。这给了我AppDelegate类实例化的SIGABRT错误。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

如果你看看Xcode控制台,它应该告诉你做错了什么。

  

***因未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'不允许直接修改由标签栏控制器管理的标签栏。'

tabBar.itemsUITabBarController控制。您必须改为修改UITabBarController的viewControllers属性。

e.g:

tabBarItem3.selectedImage = UIImage(named: "tab-hash-on")


let instaViewController = UIViewController()
instaViewController.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "tab-instagram-off"), selectedImage: UIImage(named: "tab-instagram-on"))

var viewControllers = tabBarController.viewControllers!
viewControllers.append(instaViewController)
tabBarController.viewControllers = viewControllers


return true