You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯代码实现UITabBarController时TabBar项需点击才显示的问题

解决纯代码创建UITabBarController时标签栏图标初始不显示问题

问题的核心原因是未给UITabBarItem设置标题,或未正确初始化完整的标签栏项,导致初始布局时图标无法正常渲染。以下两种方式可修复该问题:

方式一:直接初始化完整的UITabBarItem

修改SceneDelegate中的代码,替换原有设置tabBarItem的片段:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    let window = UIWindow(windowScene: windowScene)
    
    let tabBarController = UITabBarController()
    
    let vc1 = UINavigationController(rootViewController: MoviesScreen())
    // 初始化包含标题、图标的完整标签栏项
    vc1.tabBarItem = UITabBarItem(
        title: "Movies",
        image: UIImage(systemName: "film"),
        selectedImage: UIImage(systemName: "film.fill")
    )
    
    let vc2 = UINavigationController(rootViewController: FavouritesScreen())
    vc2.tabBarItem = UITabBarItem(
        title: "Favourites",
        image: UIImage(systemName: "heart"),
        selectedImage: UIImage(systemName: "heart.fill")
    )
    
    tabBarController.setViewControllers([vc1, vc2], animated: false)
    
    window.rootViewController = tabBarController
    self.window = window
    window.makeKeyAndVisible()
}

方式二:给根视图控制器设置UITabBarItem

导航控制器默认会继承根视图控制器的tabBarItem,因此也可以在子控制器中直接设置:

class MoviesScreen: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Movies"
        view.backgroundColor = .red
        // 为当前控制器配置标签栏项
        tabBarItem = UITabBarItem(
            title: "Movies",
            image: UIImage(systemName: "film"),
            selectedImage: UIImage(systemName: "film.fill")
        )
    }
}

class FavouritesScreen: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Favourites"
        view.backgroundColor = .yellow
        tabBarItem = UITabBarItem(
            title: "Favourites",
            image: UIImage(systemName: "heart"),
            selectedImage: UIImage(systemName: "heart.fill")
        )
    }
}

原因说明

仅设置tabBarItem的image和selectedImage而缺失标题时,标签栏项的布局计算会出现异常,导致图标无法在初始状态下渲染。点击标签栏区域会触发布局更新,图标才会显示。通过初始化包含标题的完整UITabBarItem,系统能正确计算标签栏项的布局空间,确保图标从启动时就正常显示。

内容的提问来源于stack exchange,提问作者Abdullah Ajmal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:03:10