iOS 18中UITabBarItem偶尔左对齐显示的问题及解决
iOS 18 UITabBarItem 偶尔左对齐问题的修复方案
针对iOS 18下UITabBarItem偶尔出现左对齐的异常,结合你提供的代码,给出以下几个可行的修复思路:
1. 强制指定UITabBar布局规则
iOS 18可能调整了UITabBar的默认布局逻辑,手动设置item的定位方式和间距,确保所有item均匀分布:
在你的configureTabbar()方法中添加iOS 18适配代码:
func configureTabbar() { UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)], for: .selected) tabBar.barTintColor = UIColor.theme.tabBarBackgroundColor tabBar.isTranslucent = false tabBar.tintColor = UIColor.theme.tabbarItemSelectedColor tabBar.unselectedItemTintColor = UIColor.theme.tabbarItemNormalColor // iOS 18 适配:强制item均匀填充布局 if #available(iOS 18, *) { tabBar.itemPositioning = .fill tabBar.itemSpacing = 0 // 若需要固定item宽度,可根据子控制器数量计算设置 // let itemCount = CGFloat(viewControllers?.count ?? 0) // tabBar.itemWidth = UIScreen.main.bounds.width / itemCount } }
2. 调整TabBarItem属性设置时机
确保TabBarItem的属性设置在控制器被添加到UITabBarController之后完成,避免布局时属性未完全生效。可以将相关设置移到viewDidLoad中:
修改导航控制器的初始化方法,延迟TabBarItem属性设置:
// 先定义实例变量存储参数 private let tabTitle: String private let tabImage: String private let useSysImage: Bool init(title: String = "", image: String = "", sysImaged: Bool = true, rootViewController: UIViewController) { self.tabTitle = title self.tabImage = image self.useSysImage = sysImaged super.init(rootViewController: rootViewController) self.title = tabTitle self.navigationBar.barStyle = .black self.modalPresentationStyle = .fullScreen self.navigationBar.tintColor = UIColor.white self.delegate = self if #available(iOS 15, *) { UINavigationBar.appearance().scrollEdgeAppearance = UINavigationBarAppearance() } } override func viewDidLoad() { super.viewDidLoad() // 在viewDidLoad中设置TabBarItem属性 if useSysImage { self.tabBarItem.image = UIImage(systemName: tabImage)?.withRenderingMode(.alwaysTemplate) self.tabBarItem.selectedImage = UIImage(systemName: "\(tabImage).fill")?.withRenderingMode(.alwaysTemplate) } else { self.tabBarItem.image = UIImage(named: tabImage)?.withRenderingMode(.alwaysTemplate) self.tabBarItem.selectedImage = UIImage(named: "\(tabImage)_sel")?.withRenderingMode(.alwaysTemplate) } self.tabBarItem.imageInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2) }
3. 检查全局Appearance配置冲突
排查项目中是否有其他地方通过UITabBar.appearance()设置过itemPositioning、itemWidth等布局相关属性,统一在configureTabbar()中集中配置,避免属性冲突导致布局异常。
4. 强制触发TabBar布局更新
如果问题为偶发,可以在UITabBarController的viewDidAppear中强制触发布局刷新:
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if #available(iOS 18, *) { tabBar.setNeedsLayout() tabBar.layoutIfNeeded() } }
以上方案均针对iOS 18的布局逻辑变化,通过显式控制布局参数来规避系统默认布局的异常。
内容的提问来源于stack exchange,提问作者jrjian
相关产品推荐
相关产品推荐

