Swift中选定的tabBar项目透明背景

时间:2020-09-09 11:12:56

标签: swift uitabbarcontroller uitabbar uicolor uitabbaritem

这里有两种颜色:

androidx.preference:preference:1.1.1

我为barTint颜色设置了static let mainDarkBlue = UIColor(r: 40, g: 51, b: 86) static let mainDarkBlueTransparent = UIColor(r: 40, g: 51, b: 86, a: 0.8) ,这很好,但是有mainDarkBlue我想成为选定的tabBar项的背景颜色。

mainDarkBlueTransparent

那很好,但是我想让我的两个项目处于选中状态和未选中状态之间。
另外,如果有人知道如何制作选中项目的阴影,请告诉我。

1 个答案:

答案 0 :(得分:0)

要为选定的tabBar项设置背景色,您可以执行以下操作:

extension UIColor {
    func image(_ size: CGSize = CGSize(width: 71, height: 48)) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { rendererContext in
            self.setFill()
            rendererContext.fill(CGRect(origin: .zero, size: size))
        }
    }
}

此扩展名可用于将颜色转换为图像。然后,该图像可用作selectionIndicatorImage

tabBar.selectionIndicatorImage = UIColor.mainDarkBlueTransparent.image()

为更加灵活,您还可以执行以下操作(基于vpoltave提供的链接):

let numberOfItems = CGFloat(tabBar.items!.count)//make sure that items isn't nil -> maybe you should use some if let or guard instead + make sure that your are executing this code after you have set the tabBarItems
let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
tabBar.selectionIndicatorImage = UIColor.mainDarkBlueTransparent.image(tabBarItemSize)