3

I am new to iOS.I want to apply gradient colors on CarbonTabSwipeNavigation.I tried to apply the gradient to the toolbar of CarbonTabSwipeNavigation, but it is not happening I have tried with Static Colore Code

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))
dpapadopoulos
  • 1,834
  • 5
  • 23
  • 34
Vishal Shelake
  • 572
  • 1
  • 8
  • 12
  • Consider marking an answer as correct to expand the visibility of the question: [stackoverflow.com/help/someone-answers](https://stackoverflow.com/help/someone-answers) – Nilesh R Patel Feb 20 '19 at 05:03

1 Answers1

0

First, add these extensions in your project.

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
    }

}

Then call this method as your requirement.

Example:- If you want to set a gradient color on navigationbar of your app then call use this

self.navigationController?.navigationBar.setGradientBackground(colors: [UIColor.black, UIColor.red])
Nilesh R Patel
  • 697
  • 7
  • 17