简体   繁体   English

无法设置标签栏项目

[英]Can't set tab bar items

I am trying to set the items for my Tab Bar from the TabBarViewController. 我正在尝试从TabBarViewController为我的Tab栏设置项目。

However, once I set the items, here's the error I get: 但是,一旦我设置了项目,这是我得到的错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Directly modifying a tab bar managed by a tab bar controller is not allowed.' 由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因是:'不允许直接修改由标签栏控制器管理的标签栏。'

Here's the code: 这是代码:

func imageWithImageSize(image:UIImage , newSize:CGSize) -> UIImage{

        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
        image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage

    }



    let image1 = imageWithImageSize(UIImage(named: "Home.png")!, newSize: CGSizeMake(30, 30))

    let homeItem = UITabBarItem(title: "Home", image: image1, selectedImage: image1)


    let image2 = imageWithImageSize(UIImage(named: "Profile.png")!, newSize: CGSizeMake(30, 30))
    let profileItem = UITabBarItem(title: "Profile", image: image2, selectedImage: image2)


    self.tabBar.setItems([homeItem,profileItem, homeItem, homeItem], animated: false)

Is there a solution around it? 周围有解决方案吗?

you cant modify them directly instead you can do the following things. 你不能直接修改它们,而是可以做以下事情。

1.Get the UITabBarController in which you want to add tabs.suppose you have tabBarController with name tabController. 1.获取要在其中添加tab的UITabBarController。假设您有tabBarController,其名称为tabController。

2.Get all the viewController of tabController. 2.获取tabController的所有viewController。

 guard var viewControllers = tabController.viewControllers else {
      return
    }

3.get your view controller. 3.注意你的视图控制器。 for ex. 对于前 we take exampleVC. 我们以exampleVC为例。

4.create tabBarItem for exampleVC 4.为exampleVC创建tabBarItem

let performanceTabItem = UITabBarItem(title: "example", image: "tabImage", selectedImage: "selectedTabImage" )

5.set 5.设置

exampleVC.tabBarItem = performanceTabItem

6.append exampleVC with viewControllers 6.使用viewControllers实现exampleVC

viewControllers.append(exampleVC)

7.set viewControllers of UITabBarController. 7.set UITabBarController的viewControllers。

tabController.viewControllers = viewControllers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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