如何在Swift中为UI Tab Bar应用渐变?

5

我通过storyboard构建了选项卡栏,并通过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个回答

7

只需创建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中编写代码。

我该如何将这应用于选项卡栏的图标? - SSSS
你只需要在Storyboard中创建一个类,其余的事情就按原样工作。 - Hitesh Surani
当它来自标签栏控制器时,我该如何为其赋予一个类? - SSSS

2

步骤 1

假设您已经建立了一个选项卡栏,确保它是您的 ViewController 的代理。

step 1

第二步

在你的 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


2
如何同时填充底部安全区域? - Breno Valadão
@BrenoVinícios 不确定我的逻辑是否正确,为了填充底部,我增加了渐变层框架的高度。对我来说有效。 - Sagar Thukral

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接