如何设置carbonTabSwipeNavigation CarbonKit Cocoapods的颜色渐变

时间:2019-02-14 08:35:26

标签: ios swift xcode cocoapods carbonkit

我是iOS的新手。我想在CarbonTabSwipeNavigation上应用渐变颜色。我试图将渐变应用到CarbonTabSwipeNavigation的工具栏上,但是没有发生 我已经尝试过使用静态Colore代码

carbonTabSwipeNavigation.toolbar.isTranslucent = true 
var color1 = hexStringToUIColor(hex: "#00275E")
carbonTabSwipeNavigation.carbonSegmentedControl?.backgroundColor = color1
carbonTabSwipeNavigation.setIndicatorColor(UIColor.white) //tabBar font
carbonTabSwipeNavigation.setSelectedColor(UIColor.white, font: UIFont.boldSystemFont(ofSize: 14))

1 个答案:

答案 0 :(得分:0)

首先,在您的项目中添加这些扩展名。

extension UINavigationBar {

    func setGradientBackground(colors: [UIColor]) {

        var updatedFrame = bounds
        updatedFrame.size.height += self.frame.origin.y
        let gradientLayer = CAGradientLayer(frame: updatedFrame, colors: colors)

        setBackgroundImage(gradientLayer.createGradientImage(), for: UIBarMetrics.default)
    }
}

extension UIView {

    func setGradientBackgroundOnView(colors: [UIColor]) {

        var updatedFrame = bounds
        //    updatedFrame.size.height += self.frame.origin.y
        let gradientLayer = CAGradientLayer(frame: updatedFrame, colors: colors)
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}

extension CAGradientLayer {

    convenience init(frame: CGRect, colors: [UIColor]) {
        self.init()
        self.frame = frame
        self.colors = []
        for color in colors {
            self.colors?.append(color.cgColor)
        }
        startPoint = CGPoint(x: 0, y: 1)
        endPoint = CGPoint(x: 1, y: 1)
    }

    func createGradientImage() -> UIImage? {

        var image: UIImage? = nil
        UIGraphicsBeginImageContext(bounds.size)
        if let context = UIGraphicsGetCurrentContext() {
            render(in: context)
            image = UIGraphicsGetImageFromCurrentImageContext()
        }
        UIGraphicsEndImageContext()
        return image
    }

}

然后根据需要调用此方法。

示例:-如果您要在应用的gradient上设置navigationbar颜色,请使用此颜色

self.navigationController?.navigationBar.setGradientBackground(colors: [UIColor.black, UIColor.red])