1

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

4

2 回答 2

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];

}

希望对你有帮助..

于 2017-07-07T09:40:15.537 回答
-2

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

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

UITabBarController *tabBarCon;
...
tabBarCon.tabBar.tintColor = [UIColor blueColor];
于 2012-05-29T12:57:35.243 回答