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

标签 objective-c ios uinavigationbar uitabbar background-color

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

最佳答案

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

}

希望对你有帮助

关于objective-c - 在 objective-c 中使用渐变设置 NavigationBar 和 TabBar 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10799561/

相关文章:

ios - UITextField .text 属性总是返回一个空字符串

android - 如何使用 flutter 创建单一后端网站、iOS 应用程序和 Android 应用程序?

iOS 11 问题与 navigationBar prefersLargeTitles

ios - UINavigationBar 滑开而不是停留在原地

ios - 符合协议(protocol)的 id 与使用协议(protocol)限定 id

ios - ios中如何将nsstring格式转为json响应格式?

ios - ios中出现UISwipeGestureRecogniser时的UIImageView动画

ios - 为什么建议在注册推送通知服务之前调用 registerUserNotificationSettings

iOS 检测模拟位置

swift - 如何在 swift3 中更改导航 Controller 上的后退按钮标题?