将标签栏项添加到UITabBar时出现问题

Aqu*_*eel 7 iphone objective-c uitabbarcontroller uitabbaritem uitabbar

我有一个基于标签栏的应用程序,我试图使用setItems方法动态地将标签栏项添加到标签栏UITabBar.

这是代码:

[self.tabBarController.tabBar setItems:self.level1TabBarItems animated:YES];
Run Code Online (Sandbox Code Playgroud)

哪里self.level1TabBarItems是一个NSMutableArray有4个UITabBarItems在里面.当我运行此代码时,我从编译器中获得异常.

NSInternalInconsistencyException,原因:不允许直接修改由选项卡栏控制器管理的选项卡栏.

我已经尝试删除UITabBarViewController并再次添加它但它不起作用.

Dee*_*olu 13

The documentation明确指出不应直接修改标签栏.请setViewControllers:animated:改用.


小智 6

我希望可以通过以下代码为您提供帮助:

func application(_application: UIApplication,
                didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = LongUITabBarController()
    window?.makeKeyAndVisible()

    return true
}
import UIKit


class LongUITabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let vc1 = VC1_ViewController()
        let vc2 = VC2_ViewController()
        let vc3 = VC3_ViewController()
        let vc4 = VC4_ViewController()

        vc1.tabBarItem = UITabBarItem(title: "LIST ALL", image: UIImage(named: "list"), tag: 1)
        vc2.tabBarItem = UITabBarItem(title: "BEST CELLER", image: UIImage(named: "bestCeller"), tag: 2)
        vc3.tabBarItem = UITabBarItem(title: "MOST LIKE", image: UIImage(named: "like"), tag: 3)
        vc4.tabBarItem = UITabBarItem(title: "NEW", image: UIImage(named: "new"), tag: 4)

        viewControllers = [vc1, vc2, vc3, vc4]
        setViewControllers(viewControllers, animated: true)

        // backGround for tapBarView
        tabBar.barTintColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)

    }


}
Run Code Online (Sandbox Code Playgroud)