如何自定义从对象库添加的导航栏?解决现有代码失效问题
当然可以自定义从对象库添加的独立导航栏!
你遇到的问题很常见——原来的代码是针对UINavigationController自带的导航栏,但从对象库拖到视图里的是独立的UINavigationBar实例,它和self.navigationController没有关联,所以你的代码根本没作用到这个自定义导航栏上。
解决步骤很简单:
首先在你的ViewController里给这个自定义导航栏添加一个IBOutlet关联:
- 打开Storyboard,选中你拖进来的导航栏
- 按住Control键拖到ViewController的代码文件里,创建一个名为
customNavBar的IBOutlet属性
把你原来的代码改成直接操作这个
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
相关产品推荐
相关产品推荐

