ios - 在 iOS 中更改 uiTabBarItem 的可调整大小的背景图像/颜色

标签 ios uitabbar

我需要做一个相当简单的任务。

我有一个标签栏,需要在选中时更改栏的背景颜色。

我一直在寻找解决方案的尴尬时间。

大多数指南都谈到了 TabBarItem 的 SelectedImage 属性,但我需要这个东西的大小完全动态。一张图片在一台设备上只能适应一个方向。

这是我要完成的截图:

enter image description here

理想情况下,我只想将选定的选项卡背景颜色设置为白色。有人可以告诉我如何做到这一点吗?

非常感谢!

最佳答案

张贴这个以防以后有人需要它。

此解决方案由三部分组成。

第 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/

相关文章:

ios - 进行服务调用时如何设置输入参数

ios - UITabBarItem - 所有项目在首次启动时显示 selectedImage

ios - 使标签栏应用程序中的更多按钮在 iOS 中滑出

swift 3 : UITabBarController error: '*** -[__NSArray0 objectAtIndex:]: index 1 beyond bounds for empty NSArray'

objective-c - TvOS UITabBarController 检测标签栏显示/隐藏

ios - UITabbar 项目在升级到 Xcode 7 后单击后才会显示

ios - 无法运行 iOS UI 自动化的命令行

ios - GMSSyncTileLayer 类 --- 如何传递我的 mapView? ..x 和 y 到底是什么?

android - Flutter 从 Assets 文件夹中读取所有文件

ios - Swift 3 Facebook 登录