在CarbonTabSwipeNavigation

在CarbonTabSwipeNavigation

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

最佳答案

问题在于gradientLayer框架。Toolbar对其调用setGradientToToolbar方法时,约束尚未布局。所以,当一切都为零时,你就看不到梯度层。
有两种方法可以解决这个问题,
1)您为bounds提供如下框架,

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

都会给你下面的结果,
ios - 在CarbonTabSwipeNavigation上应用渐变颜色-LMLPHP

关于ios - 在CarbonTabSwipeNavigation上应用渐变颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50342329/

10-10 20:54