首页 > 解决方案 > 试图找到自定义标签栏的更好方法

问题描述

我正在尝试创建一个自定义TabBar. 到目前为止,我的方法是创建一个UIViewController(我们称之为TabBarController),在 中TabBarController,我添加了一个childVC(我们称之为UserViewController)。

我想不出一种方法来改变UserViewController不让TabBarController消失。

我开始认为这可能不是一个好的选择,而且大多数情况下都有更好的、实际可行的方法来做到这一点。我真正想要实现的只是一个TabBarController,与 分开UserViewControllerTabBarController将始终显示在屏幕底部,通过单击其中的项目,UserViewController将相应地更改。

我搜索了几个小时,尝试了不同的解决方案,但没有任何效果。真的希望您能指导我,也许分享您对此的教程或文章。

标签: iosswift

解决方案


创建 的子类UITabBarViewController

 class TabBarController: UITabBarController {

    var previousTabIndex: Int?

    override func viewDidLoad() {
        super.viewDidLoad()

        let viewControllerOne = ViewController()
        viewControllerOne.tabBarItem.image =  UIImage(named: "one")
        viewControllerOne.tabBarItem.title = "One"

        let viewControllerTwo = ViewController()
        viewControllerTwo.tabBarItem.image =  UIImage(named: "two")
        viewControllerTwo.tabBarItem.title = "Two"

        let viewControllerThree = ViewController()
        viewControllerThree.tabBarItem.title = "Premium"
        viewControllerThree.tabBarItem.image =  UIImage(named: "three")

        let tabBarList = [
            viewControllerOne,
            viewControllerTwo,
            viewControllerThree
        ]

        self.viewControllers = tabBarList.map {
            let nav = UINavigationController(rootViewController: $0)
            return nav
        }
    }
}

然后在SceneDelegate, 设置 window.rootViewController = TabBarController()

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = TabBarController()
        self.window = window
        window.makeKeyAndVisible()
    }
}

如果您在旧版本的 xCode 中创建了项目,请分配TabBarController()window.rootControllerin didFinishLaunchingWithOptionsofAppDelegate


推荐阅读