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

How to apply a gradient on a UI Tab Bar In Swift?

我通过情节提要构建了标签栏,并在应用程序委托中更改了自定义颜色,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)

}

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

第 1 步

假设您已经以这种方式构建了一个标签栏,请确保它是您 ViewController 的代表。

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

    }
}

结果

只需创建 UITabBarController

的子class
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 class 而不是 UITabBarController

此方法的主要优点如下。

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