获取UINavigationBar对象
在开发中我们的项目大部分页面的导航栏风格是一致的,所以我们在设置nav样式的时候基本都会采用全局设置的方式来达到目的。那么怎么获取到这个全局对象呢?来看下面的代码:
UINavigationBar *bar = [UINavigationBar appearance];
一行代码就拿到了想要的对象,下面就可以对它进行各种你想要的设置了。
修改导航栏背景色(图片)
//设置背景颜色
[bar setBarTintColor:[UIColor whiteColor]];
bar.translucent = NO;//如果你不需要系统自动的半透明效果就加上这行代码就可以达到想要的效果了
//设置背景图片
[navBar setBackgroundImage:[UIImage imageNamed:@"imageName"] forBarMetrics:UIBarMetricsDefault];
导航栏标题的设置
//设置导航栏标题的样式,参数为一个富文本属性字典
[bar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:16]}];
//你可以根据自己的需求来设置下面这些属性
//系统提供的所有富文本属性
NSFontAttributeName // 设置字体
NSParagraphStyleAttributeName // 设置段落风格
NSForegroundColorAttributeName // 设置文字颜色
NSBackgroundColorAttributeName // 设置背景颜色
NSLigatureAttributeName // 设置连体属性
NSKernAttributeName // 设置字符间距
NSStrikethroughStyleAttributeName // 添加删除线
NSUnderlineStyleAttributeName // 添加下划线
NSStrokeColorAttributeName // 设置文字描边颜色
NSStrokeWidthAttributeName // 设置文字描边宽度
NSShadowAttributeName // 设置阴影
NSTextEffectAttributeName // 设置文本特殊效果
NSAttachmentAttributeName // 设置文本附件
NSLinkAttributeName // 设置链接属性
NSBaselineOffsetAttributeName // 设置基线偏移量
NSUnderlineColorAttributeName // 添加下划线颜色
NSStrikethroughColorAttributeName // 添加删除线颜色
NSObliquenessAttributeName // 设置字体倾斜
NSExpansionAttributeName // 设置文本扁平
NSWritingDirectionAttributeName // 设置文字书写方向
NSVerticalGlyphFormAttributeName // 设置文本段落排版格式
导航栏底部自带线条的去除
//方法1:实例一个图片对象将系统的图片对象覆盖掉
[bar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[bar setShadowImage:[[UIImage alloc] init]];
//方法2:将clipsToBounds属性设置为YES裁剪掉阴影部分
bar.clipsToBounds = YES;
导航栏返回按钮的设置
//修改返回图片颜色
[bar setTintColor:[UIColor whiteColor]];//这里注意要把tintColor和barTintColor两个属性区分开
//去掉文字仅显示返回图标
//由于设置的是navBar上的一个item的属性所以无法通过appearance来获取对象所以需要换一种方式来达到全局设置的目的
//一般我用会采用抽取父类或者为系统nav类添加分类,然后重写系统push方法的方式来修改。如下:
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc ]initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
[super pushViewController:viewController animated:animated];
}
最后加餐UIBarButtonItem的自定制以及位置调整
相信大家也经常使用下面这个方法:
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:view];
这里我就不多说什么了,想要什么样的视图自己做出来就好了,我就主要分享下位置调整的方法。
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
space.width = -15;
self.navigationItem.rightBarButtonItems = @[space,item];
实例一个占位item通过调整该item的宽度来设置其它item的位置。(leftBarButton也可以这样做)
最近公司新启了一个项目,我也是刚刚又做了一遍这些设置。然后就想趁这个机会把项目中一些常用的功能总结总结,来和大家分享一下。希望能帮到大家~
网友评论