1. 程式人生 > >ios 導航欄透明, 上下滑動 導航欄 顏色漸變

ios 導航欄透明, 上下滑動 導航欄 顏色漸變

滾動 pear action 文字 oid ati scom compact arm

- (void)viewWillAppear:(BOOL)animated {

//設置導航欄背景圖片為一個空的image,這樣就透明了

[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsCompact];

//去掉透明後導航欄下邊的黑邊

// [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];

self.navigationController.navigationBar.translucent = YES;//這個必須設置

}

- (void)viewWillDisappear:(BOOL)animated {

// 返回時不讓其他頁面的導航欄變為透明 需要重置

[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsCompact];

// [self.navigationController.navigationBar setShadowImage:nil];

self.navigationController.navigationBar.translucent = NO;

}

//如果要監聽滾動而使導航欄顏色漸變,在scrollView的代理方法中添加代碼

-(void)scrollViewDidScroll:(UIScrollView *)scrollView

{

//滑動漸變顏色

[self.navigationController.navigationBar setBackgroundImage:[self imageWithBgColor:[UIColor colorWithRed:18/255.0 green:151/255.0 blue:171/255.0 alpha:self.myTableView.contentOffset.y /100]] forBarMetrics:UIBarMetricsDefault];// 顏色自己設置 漸變開始的位置自己算

}

-(UIImage *)imageWithBgColor:(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 *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return image;

}

/*------------導航欄常用屬性--------*/

  1. 導航欄背景色設置:

    self.navigationController.navigationBar.barTintColor = [UIColor greenColor];

  2. 導航欄標題顏色字體大小

    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];

    attrs[NSForegroundColorAttributeName] = [UIColor whiteColor];

    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:17];

    [self.navigationController.navigationBar setTitleTextAttributes:attrs];

  3. 導航欄左右item

    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"left" style:UIBarButtonItemStylePlain target:self action:@selector(left)];

    self.navigationItem.leftBarButtonItem = leftItem;

    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"right" style:UIBarButtonItemStylePlain target:self action:@selector(right)];

    self.navigationItem.rightBarButtonItem = rightItem;

  4. 導航欄item字體顏色

    self.navigationController.navigationBar.tintColor = [UIColor redColor];如果要不同item不同顏色,那麽item要帶一個自定義按鈕,在設置按鈕屬性

  5. 當前控制器的下一個控制器的返回item去掉文字只保留箭頭

    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(back)];

    self.navigationItem.backBarButtonItem = backItem;

ios 導航欄透明, 上下滑動 導航欄 顏色漸變