UINavigationController是常用的控件,经常会修改navigationBar的样式,
一.设置navigationBar的背景颜色
首先:效果图(设置navigationbar背景为红色)
上面效果对应的代码如下:
在appdelegate中设置:
1️⃣
UINavigationBar *bar = [UINavigationBarappearance] ;
[bar setBarTintColor:[UIColorredColor]];//设置navigationBar的背景颜色(对应效果图最外层红色)
[bar setTitleTextAttributes:@{UITextAttributeTextColor : [UIColorblueColor]}];//设置字体颜色
在viewController中设置
2️⃣
self.navigationItem.title =@"呵呵呵哒";
self.navigationController.navigationBar.backgroundColor = [UIColor yellowColor];//也是设置背景颜色,(对应效果图中内层黄色)
self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
实际上1️⃣修改的是红色箭头对应的内容
2️⃣修改的是黄色箭头对应的内容 只是红色把黄色覆盖了
navigationBar
最后显示为红色,所以结果显而易见 想要改变navigationBar的背景色,只有用这种方法:
UINavigationBar *bar = [UINavigationBar appearance] ;
[bar setBarTintColor:[UIColor redColor]];
二.动态修改navigationBar的背景颜色,类似qq空间
首先想到的就是在滑动scrollView时动态修改背景颜色的透明度,或者修改背景颜色,但实际操作时发现不可行
官方解释:
Use the UIAppearance protocol to get the appearance proxy for a class. You can customize the appearance of instances of a class by sending appearance modification messages to the class’s appearance proxy.
iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window. To change the appearance of a view that’s currently in a window, remove the view from the view hierarchy and then put it back.
我的理解是:navigationBar已经创建成功,外观经不再发生变化,除非重绘视图(删除背景视图重新添加),否则外观将不会发生变化。
解决办法
1️⃣:隐藏navigationBar,自己重写一个view代替navigationBar的功能
2️⃣:替换navigationBar:重写一个naviagationBar继承系统的navigationBar,在哪个红色背景之上添加一个view,我们可以动态的改变该view颜色
考虑到继承UINavigationBar使用起来会非常不便,我们决定用Category来实现,首先定义我们的category:
1
2
3
|
@interface UINavigationBar (BackgroundColor)
- (void)lt_setBackgroundColor:(UIColor *)backgroundColor;
@end
|
实现:我们使用associatedObject将overlayView动态地绑定到UINavigationBar的instance上,当调用lt_setBackgroundColor的时候,我们只要更新这个overlayView就行啦~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@implementation UINavigationBar (BackgroundColor)static char overlayKey;
- (UIView *)overlay
{
return
objc_getAssociatedObject(self, &overlayKey);
}
- (void)setOverlay:(UIView *)overlay
{
objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)lt_setBackgroundColor:(UIColor *)backgroundColor
{
if
(!self.overlay) {
[self setBackgroundImage:[UIImage
new
] forBarMetrics:UIBarMetricsDefault];
[self setShadowImage:[UIImage
new
]];
// insert an overlay into the view hierarchy
self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, 64)];
[self insertSubview:self.overlay atIndex:0];
} self.overlay.backgroundColor = backgroundColor;
}@end
|
http://blog.csdn.net/mad1989/article/details/41516743