如何在Swift中的UI标签栏上应用渐变?

时间:2019-05-05 21:42:46

标签: ios swift uitabbar

我通过情节提要构建了选项卡栏,然后使用UITabBar.appearance().barTintColor = Color在应用程序委托中更改颜色以自定义

我有一个这样的渐变方法:

func setGradientBackground(colorOne: UIColor, colorTwo: UIColor)  {
    let gradientlayer = CAGradientLayer()
    gradientlayer.frame = bounds
    gradientlayer.colors = [colorOne.cgColor, colorTwo.cgColor]
    gradientlayer.locations = [0, 1]
    gradientlayer.startPoint = CGPoint(x: 1.0, y: 0.0)
    gradientlayer.endPoint = CGPoint(x: 0.0, y: 0.0)

    layer.insertSublayer(gradientlayer, at: 0)

}

如何将其应用于标签栏的背景?

2 个答案:

答案 0 :(得分:1)

只需创建UITabBarController的子类

class GradientTabBarController: UITabBarController {

        let gradientlayer = CAGradientLayer()

        override func viewDidLoad() {
            super.viewDidLoad()
            setGradientBackground(colorOne: .yellow, colorTwo: .red)
        }

        func setGradientBackground(colorOne: UIColor, colorTwo: UIColor)  {
            gradientlayer.frame = tabBar.bounds
            gradientlayer.colors = [colorOne.cgColor, colorTwo.cgColor]
            gradientlayer.locations = [0, 1]
            gradientlayer.startPoint = CGPoint(x: 1.0, y: 0.0)
            gradientlayer.endPoint = CGPoint(x: 0.0, y: 0.0)
            self.tabBar.layer.insertSublayer(gradientlayer, at: 0)
        }
}

在情节提要中分配GradientTabBarController类,而不是UITabBarController

这种方法的主要优点如下。

  1. 无需定义UITabBar的委托方法
  2. 无需在每个UIViewController中编写代码

答案 1 :(得分:0)

步骤1

假设您以这种方式构建了标签栏,请确保它是您的ViewController的委托。

step 1

步骤2

在您的ViewController.swift中,使用以下代码:

import UIKit

class ViewController: UIViewController, UITabBarDelegate {

    @IBOutlet weak var tabBar: UITabBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setGradientBackground(colorOne: .blue, colorTwo: .red)
    }

    func setGradientBackground(colorOne: UIColor, colorTwo: UIColor)  {
        let gradientlayer = CAGradientLayer()
        gradientlayer.frame = tabBar.bounds
        gradientlayer.colors = [colorOne.cgColor, colorTwo.cgColor]
        gradientlayer.locations = [0, 1]
        gradientlayer.startPoint = CGPoint(x: 1.0, y: 0.0)
        gradientlayer.endPoint = CGPoint(x: 0.0, y: 0.0)

        self.tabBar.layer.insertSublayer(gradientlayer, at: 0)

    }
}

结果

result