1.設(shè)置translucent
屬性為NO
self.navigationController.navigationBar.translucent = YES;
translucent
是控制UINavigationBar
半透明的屬性吁朦,當(dāng)translucent
設(shè)置為NO
時忍啤,UINavigationBar
下面的視圖將會下移编检,與UINavigationBar
的底部對齊胎食。如下圖示例中,UITableView
從UINavigationBar
的底部開始布局
translucent = NO;setimge = NO
從上圖可以看出UINavigationBar
里面有一個UIBarBackground
視圖允懂,其實在UIBarBackground
中有一個UIImageView
視圖(如圖2可以看出)厕怜。只有我們通過下面的代碼設(shè)置圖片才會創(chuàng)建這個UIImageView
,否則不會創(chuàng)建
- (void)setBackgroundImage:(nullable UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics
translucent = NO;setimge = YES
2.設(shè)置translucent
屬性為YES
self.navigationController.navigationBar.translucent = YES;
當(dāng)translucent
屬性設(shè)置為YES
時蕾总,UITableView
會在UINavigationBar
的下面粥航,UITableView
的頂部和UINavigationBar
對齊。默認(rèn)情況下會在UINavigationBar
的UIBarBackground
視圖中設(shè)置一個模糊視圖UIVisualEffectView
生百,如圖3躁锡。
translucent = YES;setimge = NO
當(dāng)通過setBackgroundImage:forBarMetrics:
設(shè)置背景圖片時,這個模糊視圖就不會創(chuàng)建置侍,而是創(chuàng)建一個UIImageView
映之。如下圖:
- (void)setBackgroundImage:(nullable UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics
translucent = YES;setimge = YES
總結(jié)
設(shè)置UITableView從頂部開始布局,并且讓UINavigationBar透明的方法為
- 設(shè)置
translucent
為YES
- 給
UINavigationBar
設(shè)置一個透明的背景圖
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationController.navigationBar.translucent = YES;
// shadowImage 是UINavigationBar的分割線
self.navigationController.navigationBar.shadowImage = [self createImageWithColor:[UIColor clearColor]];
[self.navigationController.navigationBar setBackgroundImage:[self createImageWithColor:[UIColor clearColor]] forBarMetrics:(UIBarMetricsDefault)];
}
// 通過顏色生成圖片
- (UIImage*)createImageWithColor:(UIColor*)color{
CGRect rect=CGRectMake(0.0f,0.0f,1.0f,1.0f);UIGraphicsBeginImageContext(rect.size);
CGContextRef context=UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage*theImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}