UITabBar在iOS7上更改一个UITabBarItem的背景颜色

Hug*_* BR 7 objective-c uitabbaritem uitabbar ios ios7

我可以改变一个特定的背景颜色UITabBarItemUITabBar

我知道如何更改所选背景的所有背景,使用:

[[UITabBar appearance] setBarTintColor:[UIColor redColor]];
[[UITabBar appearance] setTintColor:[UIColor blueColor]];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor yellowColor]];
Run Code Online (Sandbox Code Playgroud)

但是如果没有子类化,它只能用于一个项吗?

谢谢

ndb*_*ent 32

您可以将子视图添加到父tabBar,并在子视图上设置背景颜色.您可以使用tabBar框架尺寸来计算tabBarItem的偏移量和宽度,然后在下面插入子视图.

示例(在Swift中):

// Add background color to middle tabBarItem
let itemIndex = 2
let bgColor = UIColor(red: 0.08, green: 0.726, blue: 0.702, alpha: 1.0)

let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count)
let bgView = UIView(frame: CGRectMake(itemWidth * itemIndex, 0, itemWidth, tabBar.frame.height))
bgView.backgroundColor = bgColor
tabBar.insertSubview(bgView, atIndex: 0)
Run Code Online (Sandbox Code Playgroud)


fat*_*han 6

在Swift中: 此解决方案适用于使用的应用程序Auto Layout.其他解决方案的主要区别在于:tabBar.frame.width未获得实际设备的屏幕宽度.所以,bgView出现错误的地方.

你可以解决这个问题: UIScreen.main.bounds.width

let tabWidth: CGFloat = UIScreen.main.bounds.width / CGFloat(self.tabbar!.items!.count)
let tabIndex: CGFloat = 2
let bgColor: UIColor = .redColor
let bgView = UIView(frame: CGRectMake(tabWidth * tabIndex, 0, tabWidth, 49))
bgView.backgroundColor = bgColor
self.tabbar!.insertSubview(bgView, atIndex: 0)
Run Code Online (Sandbox Code Playgroud)

49是默认高度 UITabbar