导航栏选项卡栏渐变颜色

时间:2018-07-15 05:34:38

标签: ios iphone swift uinavigationcontroller gradient

这是我为Tab栏控制器编写的代码:

class TabBarUiViewController: UITabBarController {

    let layerGradient = CAGradientLayer()


    override func viewDidLoad() {

        layerGradient.colors = [UIColor.init(red: 247/255, green: 146/255, blue: 30/255, alpha: 1).cgColor, UIColor.init(red: 236/255, green: 104/255, blue: 66/255, alpha: 1).cgColor]
        layerGradient.startPoint = CGPoint(x: 0, y: 0.5)
        layerGradient.endPoint = CGPoint(x: 1, y: 0.5)
        layerGradient.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
        self.tabBar.layer.insertSublayer(layerGradient,at:0)
        self.tabBar.unselectedItemTintColor = .black

        super.viewDidLoad()

    }

}

我希望导航控制器栏具有相同的颜色和样式。 我该怎么办?正如我尝试的那样,它不像标签栏渐变那样简单 我正在寻找新的快速来源

1 个答案:

答案 0 :(得分:1)

对于标签栏: 使用addSublayer而不是insertSublayer。

TabBarUiViewController类:UITabBarController {

let layerGradient = CAGradientLayer()

override func viewDidLoad() {
    super.viewDidLoad()

    layerGradient.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor]
    layerGradient.startPoint = CGPoint(x: 0, y: 0.5)
    layerGradient.endPoint = CGPoint(x: 1, y: 0.5)
    layerGradient.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
    self.tabBar.layer.addSublayer(layerGradient)
}

}

对于导航栏:

override func viewDidLoad() {

super.viewDidLoad()

self.title = "Gradient Navigation Bar"

if let navFrame = self.navigationController?.navigationBar.frame {

  let newframe = CGRect(origin: .zero, size: CGSize(width: navFrame.width, height: (navFrame.height + UIApplication.shared.statusBarFrame.height) ))

  let image = gradientWithFrametoImage(frame: newframe, colors: [UIColor.red.cgColor, UIColor.blue.cgColor])!

  self.navigationController?.navigationBar.barTintColor = UIColor(patternImage: image)

 }
}

func gradientWithFrametoImage(frame: CGRect, colors: [CGColor]) -> UIImage? {
  let gradient: CAGradientLayer  = CAGradientLayer(layer: self.view.layer)
  gradient.frame = frame
  gradient.colors = colors
  UIGraphicsBeginImageContext(frame.size)
  gradient.render(in: UIGraphicsGetCurrentContext()!)
  let image = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  return image
 }

希望这对您有所帮助。