【问题标题】:Bottom part of tab bar does not get properly colored标签栏的底部没有正确着色
【发布时间】:2020-04-16 19:21:33
【问题描述】:

我想在我的自定义 UITabController 子类中自定义标签栏元素的颜色,并且当我这样做时它工作正常: 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]))

我无法将渐变正确应用到手机安全区域周围的标签栏底部。我在这里想念什么?看起来是这样的:

【问题讨论】:

    标签: ios objective-c swift iphone


    【解决方案1】:

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

    【讨论】:

    • 太棒了!很高兴它有帮助!
    【解决方案2】:

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

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      相关资源
      最近更新 更多