我需要做一个相当简单的任务。
我有一个标签栏,需要在选中时更改栏的背景颜色。
我一直在寻找解决方案的尴尬时间。
大多数指南都谈到了 TabBarItem 的 SelectedImage 属性,但我需要这个东西的大小完全动态。一张图片在一台设备上只能适应一个方向。
这是我要完成的截图:
理想情况下,我只想将选定的选项卡背景颜色设置为白色。有人可以告诉我如何做到这一点吗?
非常感谢!
最佳答案
张贴这个以防以后有人需要它。
此解决方案由三部分组成。
第 1 部分。 将 UITabBar 的“项目定位”属性从“自动”设置为“居中”。这将允许您设置标签栏项目的宽度。标签栏项目的高度将始终为 49。
第 2 部分。 使用此函数根据颜色和特定大小创建 UIImage:
- (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;
}
第 3 部分。 现在您已准备好实际设置选项卡项目的背景颜色。
[[UITabBar appearance] setSelectionIndicatorImage:[self imageFromColor:[UIColor whiteColor] forSize:CGSizeMake(tabBar.itemWidth, 49) withCornerRadius:0]];
为什么这不是在 Interface Builder 中实现的东西超出了我的范围。但这有效。
关于ios - 在 iOS 中更改 uiTabBarItem 的可调整大小的背景图像/颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29289475/