简体   繁体   中英

How to change the background color of tab bar programatically?

My goal is simple, change the default background color of tab bar to my own color.

For example, the default looks like this

在此处输入图片说明

I created my own subclass of UITabBarController, so that I don't need to change the color on every UIViewController

import UIKit

class MyTabController: UITabBarController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBar.backgroundColor = .black
    }
}

The result is different from what I expected.

在此处输入图片说明

I thought that maybe it's the color, then I changed to a custom UIColor and the color looks exactly the same.

I tried changing the bar tint color as well, but its change the color of the icon when active, not the background

self.tabBar.tintColor = UIColor(red:1.00, green:0.23, blue:0.19, alpha:1.0)

The result will be

在此处输入图片说明

What did I do wrong?

您应该使用self.tabBar.barTintColor或看看UIBarStyleself.tabBar.barStyle看看是否可行

I had the same problem with my app but I wanted to set up a gradient image in tabbar background and I came up with following: in applicationDidFinishLaunching method I created a function to draw a gradient and used an instance of my UITabBarController to set up a correct gradient frame depending on the width of the device.

- (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));

    //set up your gradient
    //......

    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return gradientImage;
}

get the instance of UITabBarController

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

set your gradient

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

I'm not sure if that's a correct approach but it did work for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM