使用objective-c中的渐变设置NavigationBar和TabBar背景颜色

时间:2012-05-29 12:51:55

标签: objective-c ios uinavigationbar uitabbar background-color

我想为NavigationBar和TabBar设置背景颜色。它必须是包含两个十六进制颜色的渐变。我怎样才能在Objective-c中做到这一点? 谢谢,

2 个答案:

答案 0 :(得分:0)

对于TabBar,我的应用程序遇到了同样的问题,我想出了以下内容: 在 applicationDidFinishLaunching 方法中,我创建了一个绘制渐变的函数,并使用我的UITabBarController实例根据设备的宽度设置正确的渐变框架。

    - (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
   CAGradientLayer *gradient = [CAGradientLayer layer];

  gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));

  gradient.colors = @[(__bridge id)[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
  gradient.startPoint = CGPointMake(0.0, 0.5);
  gradient.endPoint = CGPointMake(0.5, 0.5);

  UIGraphicsBeginImageContext(gradient.bounds.size);
  [gradient renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return gradientImage;
} 

获取UITabBarController的实例

UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;

设置渐变

[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];

我不确定这是否是正确的方法,但它对我有用。

对于NavigationBar,我将其子类化并在 layoutSubviews 中自定义

- (void)layoutSubviews {
    [super layoutSubviews];

    CAGradientLayer *gradient = [CAGradientLayer layer];

    gradient.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + CGRectGetHeight([UIApplication sharedApplication].statusBarFrame));
    gradient.colors = @[(__bridge id)[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
    gradient.startPoint = CGPointMake(0.0, 0.5);
    gradient.endPoint = CGPointMake(0.5, 0.5);

    UIGraphicsBeginImageContext(gradient.bounds.size);
    [gradient renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setBackgroundImage:gradientImage forBarMetrics:UIBarMetricsDefault];

}

希望这会对你有帮助..

答案 1 :(得分:-2)

这将帮助您更改导航栏的颜色。标签栏

UINavigationController *navigationController;
...
navigationController.navigationBar.tintColor = [UIColor blackColor];

UITabBarController *tabBarCon;
...
tabBarCon.tabBar.tintColor = [UIColor blueColor];