我通过故事板构建了选项卡栏,并自定义颜色,我在应用程序委托中更改它,使用
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)
}
如何将其应用到标签栏的背景?
只需创建
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
此方法的主要优点如下。
UITabBar
UIViewController
假设您已经以这种方式构建了一个选项卡栏,请确保它是您的
ViewController
的委托。
在您的
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)
}
}
✅ 快速解决方案,这将用渐变完全填充背景
func setTabGradientBackground(frame: CGRect ,colorOne: UIColor, colorTwo: UIColor, insertTo: CALayer ) {
let gradientlayer = CAGradientLayer()
gradientlayer.name = "GradientLayerKey"
gradientlayer.frame = frame
gradientlayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientlayer.locations = [0, 1]
gradientlayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientlayer.endPoint = CGPoint(x: 1.0, y: 1.0)
insertTo.insertSublayer(gradientlayer, at: 0)
}
使用方法
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setTabGradientBackground(
frame: tabBar.bounds,
colorOne: .blue,
colorTwo: .red,
insertTo: tabBar.layer
)
}