1

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 working. Here's the code.

let carbonTabSwipeNavigation = CarbonTabSwipeNavigation(items: items, delegate: self)
carbonTabSwipeNavigation.toolbar.setGradientToToolbar(default_pri_color: UIColor.DarkBlue(), default_sec_color: UIColor.LightBlue())

Here's the Function

extension UIToolbar {

    func setGradientToToolbar(default_pri_color: UIColor, default_sec_color: UIColor) {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [default_pri_color.cgColor, default_sec_color.cgColor]
        self.layer.insertSublayer(gradient, at: 0)
    }
}
Boiethios
  • 38,438
  • 19
  • 134
  • 183
Gunjan
  • 25
  • 6

1 Answers1

0

The issue is with the gradientLayer frame. Toolbar constraints are not yet laid out when you are calling setGradientToToolbar method on it. So, with everything zero in bounds you are not able to see the gradient layer.

There are two ways to fix this,

1) You provide frame for gradientLayer as below,

func setGradientToToolbar(default_pri_color: UIColor , default_sec_color:UIColor) {
    let gradient = CAGradientLayer()
    gradient.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 120)            
    gradient.colors = [UIColor.red.cgColor, UIColor.green.cgColor]
    self.layer.insertSublayer(gradient, at: 0)
}

2) Call setGradientToToolbar method on toolbar after your viewController finishes layout for all views. Below is the complete example,

import UIKit
import CarbonKit

class ViewController: UIViewController, CarbonTabSwipeNavigationDelegate {

    var carbonTabSwipeNavigation: CarbonTabSwipeNavigation!

    override func viewDidLoad() {
        super.viewDidLoad()

        let items = ["Features", "Products", "About"]
        carbonTabSwipeNavigation = CarbonTabSwipeNavigation(items: items, delegate: self)
        carbonTabSwipeNavigation.toolbarHeight.constant = 120
        carbonTabSwipeNavigation.insert(intoRootViewController: self)
    }

    func carbonTabSwipeNavigation(_ carbonTabSwipeNavigation: CarbonTabSwipeNavigation, viewControllerAt index: UInt) -> UIViewController {
        return UIViewController()
    }

    override func viewDidLayoutSubviews() {
        carbonTabSwipeNavigation.toolbar.setGradientToToolbar(default_pri_color: .red, default_sec_color: .yellow)
    }
}

extension UIToolbar {

    func setGradientToToolbar(default_pri_color: UIColor , default_sec_color:UIColor) {
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [default_pri_color.cgColor, default_sec_color.cgColor]
        self.layer.insertSublayer(gradient, at: 0)
    }
}

Both will give you the below result,

enter image description here

Kamran
  • 14,987
  • 4
  • 33
  • 51