为何UITabBarController默认背景色在iOS模拟器中不显示?
iOS 16.2模拟器中UITabBarController标签栏显示异常(真机正常)
我通过代码创建UITabBarController,实现代码如下:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { func makeItem(title: String, image: String) -> UITabBarItem { return UITabBarItem( title: NSLocalizedString(title, comment: ""), image: UIImage(systemName: image), tag: 0 ) } firstViewController = ViewController(backgroundColor: .blue) firstViewController.tabBarItem = makeItem(title: "First", image: "books.vertical.fill") secondViewController = ViewController(backgroundColor: .red) secondViewController.tabBarItem = makeItem(title: "Second", image: "books.vertical.fill") let tabBarController = UITabBarController() tabBarController.setViewControllers([firstViewController, secondViewController], animated: true) window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true }
运行后,iOS 16.2模拟器显示异常(标签栏无图标和文字):
但真机上显示正常:
环境信息:Xcode 14.2,iOS模拟器16.2,目标iOS版本13。重装Xcode、测试公开示例项目均出现相同问题。
问题原因
这是Xcode 14.x搭配iOS 16.x模拟器的已知UIKit渲染bug,系统标签栏在模拟器环境下无法正确加载SF Symbols图标及文字布局,直接通过代码初始化UITabBarItem并使用系统图标时容易触发该问题。
解决方案
提供三种可行修复方案:
修正UITabBarItem渲染设置
给系统图标指定渲染模式,同时明确标签栏的选中/未选中颜色,确保内容能正常显示:func makeItem(title: String, image: String) -> UITabBarItem { let normalImage = UIImage(systemName: image)?.withRenderingMode(.alwaysOriginal) let selectedImage = UIImage(systemName: image)?.withRenderingMode(.alwaysOriginal) let item = UITabBarItem( title: NSLocalizedString(title, comment: ""), image: normalImage, selectedImage: selectedImage, tag: 0 ) item.setTitleTextAttributes([.foregroundColor: UIColor.systemGray], for: .normal) item.setTitleTextAttributes([.foregroundColor: UIColor.systemBlue], for: .selected) return item } // 给tabBar设置全局颜色 tabBarController.tabBar.tintColor = .systemBlue tabBarController.tabBar.unselectedItemTintColor = .systemGray升级Xcode版本
苹果在Xcode 14.3及后续版本中修复了该模拟器渲染bug,升级到新版本即可解决问题。切换iOS模拟器版本
改用iOS 15.x及以下版本的模拟器,可规避该兼容性问题。
内容的提问来源于stack exchange,提问作者masterwillem
相关产品推荐
相关产品推荐

