Swift中无法去除TabBar背后灰色背景的问题求助
解决TabBar半透明时无法显示视图背景图的问题
我之前也碰到过一模一样的坑!你已经把背景图放到子视图控制器的最底层了,但半透明TabBar却显示灰色而非背景图,核心原因是半透明TabBar的穿透目标是UITabBarController的view,不是当前子视图控制器的view——默认情况下TabBarController的view背景是灰色,所以你才会看到这个颜色。
下面给你几个可行的解决方案:
方案一:给TabBarController的view添加背景图
把背景图直接加到TabBarController的view最底层,这样半透明TabBar就能穿透显示它了。在你的TabBarController类里添加这段代码:
override func viewDidLoad() { super.viewDidLoad() let background = UIImage(named: "background") let tabBarBackgroundView = UIImageView(frame: self.view.bounds) tabBarBackgroundView.contentMode = .scaleAspectFill tabBarBackgroundView.clipsToBounds = true tabBarBackgroundView.image = background self.view.insertSubview(tabBarBackgroundView, at: 0) // 你的TabBar设置 tabBar.barTintColor = UIColor.blue }
方案二:关闭TabBar的半透明(简单粗暴)
如果你的需求允许TabBar不透明,直接关闭半透明属性就行,这样barTintColor会完全覆盖,不会穿透:
tabBar.isTranslucent = false tabBar.barTintColor = UIColor.blue
不过这样就看不到背后的背景图了,适合不需要半透明效果的场景。
方案三:给TabBar设置半透明背景图(保留半透明+蓝色效果)
如果既要TabBar半透明,又要显示蓝色+透出背景图,可以放弃barTintColor,直接给TabBar设置半透明的背景图:
// 清除TabBar默认的背景和阴影 tabBar.backgroundImage = UIImage() tabBar.shadowImage = UIImage() // 生成半透明蓝色的图片 let blueTransparentImage = UIImage.colorImage(color: UIColor.blue.withAlphaComponent(0.5)) tabBar.backgroundImage = blueTransparentImage
需要给UIImage加个扩展来生成纯色图片:
extension UIImage { static func colorImage(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image ?? UIImage() } }
这样调整后,半透明TabBar就能透出TabBarController的背景图,同时保持蓝色的半透明效果啦~
内容的提问来源于stack exchange,提问作者stackich
相关产品推荐
相关产品推荐

