Reputation: 1641
I need to do a fairly simple task.
I have a tab bar, and need to change the background color of the bar when it is selected.
I have been looking for an embarrassing amount of time for a solution.
Most guides talk about the SelectedImage property of the TabBarItem, but I need this thing to be completely dynamic in size. An image would only fit one orientation on a single device.
Here is a screenshot of what I am trying to accomplish:
Ideally I would want to just set the selected tab background color to white. Could someone please tell me how this could be done?
Thanks a lot!
Upvotes: 0
Views: 649
Reputation: 1641
Posting this in case someone might need it later.
This solution is made from three parts.
Part 1. Set your UITabBar 'Item Positioning' property from Automatic to Centered. This will allow you to set the width of your tab bar items. The hight of the tab bar items will always be 49.
Part 2. Use this function to create a UIImage from a color and a specific size:
- (UIImage *)imageFromColor:(UIColor *)color forSize:(CGSize)size withCornerRadius:(CGFloat)radius
{
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContext(size);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius] addClip];
// Draw your image
[image drawInRect:rect];
// Get the image, here setting the UIImageView image
image = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
return image;
}
Part 3. Now you are ready to actually set the tab items background color.
[[UITabBar appearance] setSelectionIndicatorImage:[self imageFromColor:[UIColor whiteColor] forSize:CGSizeMake(tabBar.itemWidth, 49) withCornerRadius:0]];
Why this isn't something implemented in the Interface Builder is beyond me. But this works.
Upvotes: 1
Reputation: 4218
This may not fully solve your problem but may give you a clue that UIImage
can be dynamic in size
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode
Upvotes: 0