如何在ios 7/8中设置导航栏渐变颜色

时间:2015-02-20 15:31:11

标签: ios uinavigationbar

我正在尝试将导航和脚栏更改为深黑色灰色渐变色。 我看到改变条形颜色的方法是.navigationbar.barTintColor。 如果我只是想改变颜色,那确实有效,但我不知道如何在那里放置渐变色。

我能够为视图背景创建渐变颜色(使用cagradientlayer),但我似乎无法将其设置为导航栏背景。

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.navigationController.navigationBar.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
[self.navigationController.navigationBar.layer insertSublayer:gradient atIndex:0];

所以当我创建caGradientLayer并设置bar.layer时没有任何反应。

我尝试过CRGradientNavigationBar而且我遇到了困难。条形颜色会改变......但是我的正常根屏幕不会加载......我只看到一个白色背景

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    UINavigationController *navigationController = [[UINavigationController alloc] initWithNavigationBarClass:[CRGradientNavigationBar class] toolbarClass:nil];

    UIColor *firstColor = [UIColor colorWithRed:255.0f/255.0f green:42.0f/255.0f blue:104.0f/255.0f alpha:1.0f];
    UIColor *secondColor = [UIColor colorWithRed:255.0f/255.0f green:90.0f/255.0f blue:58.0f/255.0f alpha:1.0f];

    NSArray *colors = [NSArray arrayWithObjects:firstColor, secondColor, nil];
    // or NSArray *colors = [NSArray arrayWithObjects:(id)UIColorFromRGB(0xf16149).CGColor, (id)UIColorFromRGB(0xf14959).CGColor, nil];

    [[CRGradientNavigationBar appearance] setBarTintGradientColors:colors];
    [[navigationController navigationBar] setTranslucent:NO]; // Remember, the default value is YES.

     MasterViewController *viewController = [[MasterViewController alloc] init];
    [navigationController setViewControllers:@[viewController]];

    [self.window setRootViewController:navigationController];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;

1 个答案:

答案 0 :(得分:2)

您需要使用背景图片。制作渐变的水平可伸缩图像(使用您喜欢的图形软件,如果您想在运行时生成渐变,则使用Quartz2D)。使用-setBackgroundImage:forBarMetrics将图像应用于条形图的背景:(最好通过外观代理)。