UINavigationBar - 自定义按钮和标题
变更记录
序号 | 录入时间 | 录入人 | 备注 |
---|---|---|---|
1 | 2015-03-23 | Alfred Jiang | - |
2 | 2015-03-31 | Alfred Jiang | 更新注意问题1 |
3 | 2015-12-23 | Alfred Jiang | - |
方案名称
UINavigationBar - 自定义按钮和标题
关键字
UINavigationBar \ navigationItem \ titleView
需求场景
- 需要自定义 UINavigationBar 的按钮和标题等
参考链接
详细内容
Swift 版本
#####1. 通过 xib 文件自定义 navigationItem 的 titleView
实例化自定义对象
1
var menuTitle : REXMenuBtnView = REXMenuBtnView.loadFromNibNamed("REXMenuBtnView", bundle: nil) as REXMenuBtnView
在 viewDidLoad 中初始化必要的属性
1
2menuTitle.btnTitle.addTarget(self, action: Selector("clickTitleBtn:"), forControlEvents: UIControlEvents.TouchUpInside) //示例添加按钮响应
menuTitle.setSelected(false) //示例调用方法在 viewDidLayoutSubviews 中赋值 navigationItem
1
self.navigationItem.titleView = menuTitle
Swift 下载入自定义 xib View 方法
1
2
3
4
5extension UIView {
class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIView? {
return UINib(nibName: nibNamed,bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as? UIView
}
}
#####2. 通过 UILabel 修改 navigationItem 的 TitleView
1 | var labelTitle : UILabel = UILabel(frame: CGRectMake(0, 0, 100, 44)) |
#####3. 自定义 NavigationBar 背景图
1 | self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "login_Bg@2x"), forBarMetrics: UIBarMetrics.Default) |
#####4. 自定义 NavigationBar 按钮
1 | var backBtn : MKButton = REXTools.navRoundBtn("",frame : CGRectMake(0, 0, 12, 20), color: COLOR_GRAY,imageName: "arrowLeft", target: self, action: Selector("clickBackBtn:")) |
Objective-C 版本
1 | //NavigationBar设置背景图 |
注意问题
#####1. 设置 translucent 属性避免 UIView 向上偏移
1 | UINavigationBar.appearance().translucent = false |
以上写法在 iOS 7 环境下易造成 Crash ,需要加如下条件
1 | if (UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0 { |
或者使用下面的写法设置避免 UIView 向上偏移
1 | self.navigationController?.navigationBar.translucent = false |
效果图
(无)
备注
(无)
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 宁静至远,博雅多通!