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

如何自定义从对象库添加的导航栏?解决现有代码失效问题

当然可以自定义从对象库添加的独立导航栏!

你遇到的问题很常见——原来的代码是针对UINavigationController自带的导航栏,但从对象库拖到视图里的是独立的UINavigationBar实例,它和self.navigationController没有关联,所以你的代码根本没作用到这个自定义导航栏上。

解决步骤很简单:

  1. 首先在你的ViewController里给这个自定义导航栏添加一个IBOutlet关联:

    • 打开Storyboard,选中你拖进来的导航栏
    • 按住Control键拖到ViewController的代码文件里,创建一个名为customNavBar的IBOutlet属性
  2. 把你原来的代码改成直接操作这个customNavBar对象,替换掉self.navigationController?.navigationBar的部分:

// 直接操作自定义导航栏实例
customNavBar.tintColor = UIColor.white
customNavBar.barStyle = UIBarStyle.black
customNavBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont(name: "Chalet-NewYorkNineteenEighty", size: 37.0)!]
customNavBar.setBackgroundImage(UIImage(named: "BG.jpg")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch), for: .default)

额外提示:

  • 如果你的自定义导航栏需要显示标题、左右按钮,记得给它添加UINavigationItem(可以在Storyboard里拖进去,或者用代码创建),比如:
    let navItem = UINavigationItem(title: "你的标题")
    // 添加左侧按钮示例
    let leftBtn = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(backAction))
    navItem.leftBarButtonItem = leftBtn
    customNavBar.setItems([navItem], animated: false)
    
  • 注意字体名称要确保在项目里已经正确导入,否则UIFont(name:...)会返回nil,可能导致崩溃,建议加个可选绑定处理:
    if let customFont = UIFont(name: "Chalet-NewYorkNineteenEighty", size: 37.0) {
        customNavBar.titleTextAttributes = [NSAttributedStringKey.font: customFont]
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:47:08