在CarbonTapSwipeNavigation上应用渐变颜色

时间:2018-05-15 04:27:18

标签: ios swift carbonkit

我是iOS新手。我想在CarbonTabSwipeNavigation上应用渐变颜色。我尝试将渐变应用于CarbonTabSwipeNavigation的工具栏,但它不起作用。这是代码。

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

这是功能

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)
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于gradientLayer框架。当您在其上调用Toolbar方法时,尚未列出setGradientToToolbar个约束。因此,如果bounds中的所有内容为零,则无法看到渐变图层。

有两种方法可以解决这个问题,

1)您为gradientLayer提供了如下框架,

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)setGradientToToolbar完成所有视图的布局后,在工具栏上调用viewController方法。以下是完整的示例,

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)
    }
}

两者都会给你以下结果,

enter image description here