我通过情节提要构建了选项卡栏,然后使用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)
}
如何将其应用于标签栏的背景?
答案 0 :(得分: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
这种方法的主要优点如下。
UITabBar
的委托方法UIViewController
中编写代码答案 1 :(得分:0)
假设您以这种方式构建了标签栏,请确保它是您的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)
}
}