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

微笑、不失礼 提交于 2019-12-05 01:03:19

问题


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?


回答1:


Just create a subclass of 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)
        }
}

Assign GradientTabBarController class in the storyboard instead of UITabBarController

Main pros of this methodology are below.

  1. No need to define delegate methods of UITabBar
  2. No need to write code in each UIViewController



回答2:


Step 1

Assuming that you have built a tab bar that way, make sure it's the delegate to your ViewController.

Step 2

In your ViewController.swift use the following code:

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



来源:https://stackoverflow.com/questions/55996666/how-to-apply-a-gradient-on-a-ui-tab-bar-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!