The main problem with controlling the alpha value of a toolbar is that it applies to the entire toolbar and its buttons. If you set backgroundColor with some alpha value <1, the resulting color is combined with barStyle (UIBarStyleDefault or UIBarStyleBlack), which results in a more opaque color than the original backgroundColor . If you set barTintColor , it seems to override all other settings, including any alpha value that you set, which will result in a completely opaque color.
The only way I was able to reduce the alpha of the toolbar without affecting its buttons is to set the background image using setBackgroundImage:forToolbarPosition:barMetrics: You can create a 1px by 1px image with the desired color and alpha:
+ (UIImage *)onePixelImageWithColor:(UIColor *)color { CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 1, 1, 8, 0, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedFirst); CGContextSetFillColorWithColor(context, color.CGColor); CGContextFillRect(context, CGRectMake(0, 0, 1, 1)); CGImageRef imgRef = CGBitmapContextCreateImage(context); UIImage *image = [UIImage imageWithCGImage:imgRef]; CGImageRelease(imgRef); CGContextRelease(context); CGColorSpaceRelease(colorSpace); return image; }
[ Swift version ]
Then set the background image:
[toolbar setBackgroundImage:[self onePixelImageWithColor:[[UIColor blackColor] colorWithAlphaComponent:0.7]] forToolbarPosition:UIBarPositionBottom barMetrics:UIBarMetricsDefault];
Ryan H.
source share