【问题标题】:How to apply a gradient on a UI Tab Bar In Swift?如何在 Swift 中的 UI 标签栏上应用渐变?
【发布时间】:2019-05-05 21:42:46
【问题描述】:

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

}

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

【问题讨论】:

    标签: ios swift uitabbar


    【解决方案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中编写代码

    【讨论】:

    • 如何将它应用到标签栏的图标上?
    • 您只需要在故事板中开设一个课程,其余的事情就可以照原样进行。
    • 当它来自标签栏控制器时,我如何给它一个类?
    【解决方案2】:

    第一步

    假设您以这种方式构建了一个标签栏,请确保它是您的 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)
    
        }
    }
    

    结果

    【讨论】:

    • 如何同时填充底部安全区域?
    • @BrenoVinícios 不确定我的逻辑是否正确,为了填充底部,我增加了渐变层框架的高度。为我工作。
    猜你喜欢
    • 2022-11-12
    • 1970-01-01
    • 2018-12-23
    • 2021-08-02
    • 1970-01-01
    • 2019-03-27
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多