You need to enable JavaScript to run this app. 自定义UINavigationBar实现渐变背景与图片Logo的子类开发问题
优惠活动
大模型
产品
解决方案
定价
更多

自定义UINavigationBar实现渐变背景与图片Logo的子类开发问题

自定义UINavigationBar统一实现渐变背景、图片标题及状态栏渐变方案

原有代码核心问题

  • 标题图片设置时机错误:didMoveToSuperview生命周期阶段topItem尚未完成绑定,赋值titleView会因对象为空失效
  • 渐变层丢失:CAGradientLayer未作为属性持有,且未跟随导航栏尺寸变化更新frame,切换标签、横竖屏切换时会出现偏移或被系统层覆盖
  • 无系统新特性适配:iOS15及以上版本UINavigationBar默认的滚动边缘外观会覆盖自定义层,导致样式异常
  • 状态栏未适配:导航栏默认高度仅到状态栏底部,渐变范围无法覆盖状态栏区域

修复后完整实现代码

class NavBar: UINavigationBar {
    // 持有渐变层,避免重复创建
    private let gradientLayer = CAGradientLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonSetup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonSetup()
    }
    
    private func commonSetup() {
        // 移除系统默认背景和阴影
        setBackgroundImage(UIImage(), for: .default)
        shadowImage = UIImage()
        isTranslucent = true
        
        // 配置渐变层
        gradientLayer.colors = [UIColor.blue.cgColor, UIColor.systemTeal.cgColor] // 可自行修改渐变色
        gradientLayer.locations = [0.0, 1.0]
        layer.insertSublayer(gradientLayer, at: 0)
        
        // 适配iOS15+新外观API
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithTransparentBackground()
            appearance.backgroundImage = UIImage()
            appearance.shadowImage = UIImage()
            standardAppearance = appearance
            scrollEdgeAppearance = appearance
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 渐变层跟随导航栏尺寸更新
        gradientLayer.frame = bounds
        
        // 导航栏item加载完成后设置标题图片
        if topItem?.titleView == nil {
            let titleImageView = UIImageView(image: UIImage(named: "image"))
            titleImageView.contentMode = .scaleAspectFit
            topItem?.titleView = titleImageView
        }
    }
    
    // 延伸导航栏高度到状态栏区域,实现状态栏渐变
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        var superSize = super.sizeThatFits(size)
        let statusBarHeight = UIApplication.shared.statusBarFrame.height
        superSize.height += statusBarHeight
        return superSize
    }
}

使用方式

初始化UINavigationController时指定自定义导航栏类即可,无需在子控制器中重复配置:

let navVC = UINavigationController(navigationBarClass: NavBar.self, toolbarClass: nil)
navVC.viewControllers = [yourRootVC]

注意事项

  • 若不需要状态栏渐变,删除sizeThatFits重写方法即可
  • 标题图片需确保放入项目Asset中,名称和代码中UIImage(named:)参数一致
  • 渐变色可按需修改gradientLayer.colors数组中的色值,支持多色渐变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 04:30:02