ios - 无法设置标签栏项目

标签 ios swift uitabbarcontroller uitabbar uitabbaritem

我正在尝试从 TabBarViewController 为我的标签栏设置项目。

但是,一旦我设置了这些项目,就会出现以下错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Directly modifying a tab bar managed by a tab bar controller is not allowed.'

代码如下:

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)

有解决办法吗?

最佳答案

您不能直接修改它们,而是可以执行以下操作。

1.获取要在其中添加选项卡的 UITabBarController。假设您有名称为 tabController 的 tabBarController。

2.获取tabController的所有viewController。

 guard var viewControllers = tabController.viewControllers else {
      return
    }

3.获取你的 View Controller 。例如。我们以 VC 为例。

4.为示例VC创建tabBarItem

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

5.设置

exampleVC.tabBarItem = performanceTabItem

6.附加 exampleVC 与 viewControllers

viewControllers.append(exampleVC)

7.设置UITabBarController的viewControllers。

tabController.viewControllers = viewControllers

关于ios - 无法设置标签栏项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477041/

相关文章:

objective-c - obj-c 委托(delegate)方法为空

swift - 发现扩展时遇到的错误 : Error Domain=PlugInKit Code=13 "query cancelled"

swift - 滚动横幅 tvOS

iOS:supportedInterfaceOrientations() 的旋转问题

ios - 更改 UIViewTableCell 样式不起作用

ios - NavigationLink 内的图像不呈现

ios - 可以让 Intel Edison 充当 iOS 的 Remote

ios - 3D 触控 : Presenting From Current VC

ios - 摄像头下方有一个黑色的底部空间

ios - UISplitViewController 作为自定义选项卡栏 Controller 的子项