Skip to main content
 首页 » 操作系统

swift之更改单条条项目的背景颜色之swift

2024年01月01日67lidabo

我有一个 UITabBar,我想更改其中中间项的背景颜色,但我不知道该怎么做! (我想让栏的其余部分保持原来的深灰色)。

 let barTintColor = UIColor(red: 54/255, green: 54/255, blue: 54/255, alpha: 1.0) 
 UITabBar.appearance().barTintColor = barTintColor 

请您参考如下方法:

您可以通过向 TabBar 插入一个新的 subview 来做到这一点。
请查看 this回答:

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

希望对您有所帮助。

编辑:
如果您想更改 background image 而不是 background color,您只需更改以下行:

bgView.backgroundColor = bgColor 

以图像为背景的imageView,然后将其添加为 subview 。它可能看起来像这样:

backgroundView = UIImageView(image: UIImage(named: "tabBarImage")) 
bgView.addSubview(backgroundView)