What is the easiest way that I can achieve something like this:
Is it through subclassing a UITabBarController? If yes what property needs to be changed?
This is an old question but it comes up first in a search for TabBar gradients. A far easier way to do this is with appearances. Just put this in your applicationDidFinishLaunching method.
[[UITabBar appearance] setBackgroundImage:[UIImage imageNamed:@"navBarImage_1x49"]];
And, as a bonus, if you prefer to create a gradient image in code, you can do this:
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(0, 0, 1, 49);
gradient.colors = [NSArray arrayWithObjects:(id)[UIColor.darkGrayColor] CGColor], (id)[UIColor.blackColor] CGColor], nil];
UIGraphicsBeginImageContext(gradient.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[gradient renderInContext:context];
UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I had the same problem with my app 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.
@interface UITabBarController (private)
- (UITabBar *)tabBar;
@end
@implementation CustomizeUITabBarController
- (void)viewDidLoad {
[super viewDidLoad];
CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
UIView *v = [[UIView alloc] initWithFrame:frame];
[v setBackgroundColor:kMainColor];
[v setAlpha:0.5];
[[self tabBar] addSubview:v];
[v release];
}
@end
Hope it will help you....
Yes, subclassing an UITabbarController is the right way to do this.
Overwrite the drawRect method:
- (void)drawRect:(CGRect)rect {
[[UIImage imageNamed:@"yourNavigationBar.png"] drawInRect: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) ];
}
And add the image with gradient into your project.
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.