标签栏的底部没有正确着色

Bottom part of tab bar does not get properly colored

我想在我的自定义 UITabController 子 class 中自定义我的标签栏元素的颜色,当我这样做时它工作正常: tabBar.barTintColor = .blue(使用任何系统或自定义颜色)

但是当我尝试使用我的自定义 UIImage 扩展添加渐变时

extension UIImage {
    static func gradientImageWithBounds(bounds: CGRect, colors: [CGColor]) -> UIImage {
        let gradientLayer = CAGradientLayer()

        gradientLayer.frame = bounds
        gradientLayer.colors = colors
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
        gradientLayer.masksToBounds = true

        UIGraphicsBeginImageContext(gradientLayer.bounds.size)
        gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}

tabBar.barTintColor = UIColor(patternImage: UIImage.gradientImageWithBounds(bounds: tabBar.bounds, colors: [Colors.tabBarTopGradient, Colors.tabBarBottomGradient]))

我无法将渐变正确应用到 phone 安全区域周围的标签栏底部。我在这里错过了什么?看起来像这样:

请尝试在 viewWillLayoutSubviews() 中设置渐变色调。希望对您有所帮助!

我认为您是根据标签栏高度创建渐变,您需要的是将附加高度添加到标签栏高度

override func viewDidLoad() {
    super.viewDidLoad()

    var frame = tabBar.bounds
    let safeAreaHeight = safeAreaInsets.bottom
    frame.size.height = frame.size.height + safeAreaHeight

    tabBar.barTintColor = UIColor(patternImage: UIImage.gradientImageWithBounds(bounds: frame, colors: [UIColor.red.cgColor, UIColor.blue.cgColor]))
}

public var safeAreaInsets: UIEdgeInsets {
    guard let window: UIWindow = UIApplication.shared.windows.first else {
        return .zero
    }

    if #available(iOS 11.0, *),
        UIWindow.instancesRespond(to: #selector(getter: window.safeAreaInsets)) {
        return window.safeAreaInsets
    }

    return .zero
}