第一步、在需要導航欄透明的頁面進行設置
//允許半透明狀態
[self.navigationController.navigationBar setTranslucent:YES];
//畫一張寬為屏幕寬,高為64的透明圖片
UIColor *color = [UIColor clearColor];
CGRect rect = CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.width, 64);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//將透明圖片設為導航欄的背景圖片
[self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setBackgroundColor:[UIColor clearColor]];
//對超出父視圖的子視圖不進行裁剪
self.navigationController.navigationBar.clipsToBounds = YES;
第二步、將導航欄改為不透明
[self.navigationController.navigationBar setTranslucent:NO];
CGRect rect = CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.width, 64);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [ColorRGB(41.0, 41.0, 41.0, 1) CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.clipsToBounds = NO;