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

自定义UITabBarItem加载时意外呈灰色问题求助

解决UITabBarItem初始加载显示灰色的问题

我之前也碰到过一模一样的UITabBarItem初始化显示异常的情况,给你几个经过验证的解决方案:

1. 提前设置TabBarItem,不要在viewDidLoad里操作

viewDidLoad的调用时机晚于UITabBarController对TabBarItem的初始渲染,这就导致启动时系统先用默认样式显示,之后才会替换成你设置的图片。建议把TabBarItem的配置移到ViewController的初始化方法里:

class LocationViewController: UIViewController {
    // 自定义初始化方法
    init() {
        super.init(nibName: nil, bundle: nil)
        // 提前配置TabBarItem
        let selectedImg = UIImage(named: "LocationTabBarOn")?.withRenderingMode(.alwaysOriginal)
        let normalImg = UIImage(named: "LocationTabBarOff")?.withRenderingMode(.alwaysOriginal)
        tabBarItem = UITabBarItem(title: nil, image: normalImg, selectedImage: selectedImg)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 其他代码...
}

同样的,FavoritesViewController也用这种方式配置TabBarItem,这样在TabBarController初始化子控制器的时候,就能直接拿到正确配置的TabBarItem,避免初始显示异常。

2. 检查并设置UITabBar的未选中颜色

系统默认会给未选中的TabBarItem应用灰色的unselectedItemTintColor,虽然你设置了.alwaysOriginal,但在初始渲染阶段可能还是会有冲突。可以在自定义的UITabBarController里统一设置:

class CustomTabBarController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // 未选中状态用透明色,避免系统叠加灰色
        tabBar.unselectedItemTintColor = .clear
        // 选中状态颜色(因为用了alwaysOriginal,这个其实影响不大,但设置更稳妥)
        tabBar.tintColor = .green
    }
}

3. 验证图片资源是否正常加载

有时候图片命名错误或者资源没正确导入,会导致系统加载不到自定义图片,转而使用默认的灰色图标。可以在设置图片时加个打印验证:

guard let normalImg = UIImage(named: "LocationTabBarOff") else {
    print("LocationTabBarOff 图片加载失败!")
    return
}
guard let selectedImg = UIImage(named: "LocationTabBarOn") else {
    print("LocationTabBarOn 图片加载失败!")
    return
}
tabBarItem.image = normalImg.withRenderingMode(.alwaysOriginal)
tabBarItem.selectedImage = selectedImg.withRenderingMode(.alwaysOriginal)

总结

最核心的问题就是设置时机太晚,把TabBarItem的配置提前到ViewController初始化阶段,再配合TabBar的颜色设置,基本就能解决启动时的灰色显示问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:57:17