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

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

本文介绍了如何在Swift中的UI标签栏上应用渐变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过情节提要构建了选项卡栏,并使用 UITabBar.appearance().barTintColor = Color

I built the tab bar through the storyboard, and to customise the colour I change it in the app delegate, with UITabBar.appearance().barTintColor = Color,

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

I have a gradient method which is this:

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)

}

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

How do I apply this to the background of my tab bar?

推荐答案

只需创建 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

Assign GradientTabBarController class in the storyboard instead of UITabBarController

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

  1. 无需定义 UITabBar
  2. 的委托方法
  3. 无需在每个 UIViewController
  4. 中编写代码
  1. No need to define delegate methods of UITabBar
  2. No need to write code in each UIViewController

这篇关于如何在Swift中的UI标签栏上应用渐变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 02:49