Ios 如何在Swift中的UI选项卡栏上应用渐变?
我通过故事板构建了选项卡栏,为了定制颜色,我在应用程序委托中使用Ios 如何在Swift中的UI选项卡栏上应用渐变?,ios,swift,uitabbar,Ios,Swift,Uitabbar,我通过故事板构建了选项卡栏,为了定制颜色,我在应用程序委托中使用uitabar.appearance().barTintColor=Color,对其进行了更改 我有一个梯度法,它是这样的: func setGradientBackground(colorOne: UIColor, colorTwo: UIColor) { let gradientlayer = CAGradientLayer() gradientlayer.frame = bounds gradient
uitabar.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)
}
如何将其应用于选项卡栏的背景?步骤1
假设您以这种方式构建了一个选项卡栏,请确保它是您的视图控制器的委托
步骤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)
}
}
结果
只需创建一个子类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
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)
}
}
这种方法的主要优点如下。
无需定义uitabar的委托方法
无需在每个UIViewController
我如何将其应用于选项卡栏的图标?您只需要在故事板中提供一个类,其余的事情都按原样工作。当它来自选项卡栏控制器时,我如何提供一个类?如何填充底部安全区域?