如何给选定的TabBar渐变颜色?

问题描述 投票:0回答:1

我尝试对 UITabBar 进行子类化并应用渐变颜色,但我使用的代码将颜色添加到整个选项卡栏部分

使用的代码:

class TabViewController : UITabBarController {
   
    let gradientlayer = CAGradientLayer()
    
    override func viewDidLoad() {
       super.viewDidLoad()
    }
    
    func setUpSelectionIndicatorImage(withColors colors: [UIColor]) {
        gradientlayer.frame = tabBar.bounds
        gradientlayer.colors = [colors[0].cgColor, colors[1].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)
    }

     override func viewDidLayoutSubviews() {
        super.viewWillLayoutSubviews()
        let colors = [UIColor.IntroGradientColor1 , UIColor.IntroGradientColor2]
        setUpSelectionIndicatorImage(withColors: colors)
    }
    
}

知道如何才能仅在所选选项卡上实现这种蓝色渐变颜色,如所附图像中所示。

ios swift xcode uitabbarcontroller uitabbaritem
1个回答
0
投票

✅ 这段代码帮助我实现了这个结果!

将这些方法添加到您的

UITabBarControllerDelegate

的委托中
func clearSelections() {
    for view in tabBar.subviews {
        let gradient = view.layer.sublayers?.first(where: { layer in
            layer.name == "GradientLayerKey"
        })
        gradient?.removeFromSuperlayer()
    }
}

func setSelection(item: UITabBarItem) {
    DispatchQueue.main.async(qos: .userInteractive) {
        for i in 0..<self.tabBar.items!.count {
            let ii = self.tabBar.items![i]
            if(item == ii) {
                let sv = self.tabBar.subviews[i+1]
                sv.clipsToBounds = true
                let one = #colorLiteral(red: 0.4352941176, green: 0.7960784314, blue: 0.9921568627, alpha: 1)
                let two = #colorLiteral(red: 0.3254901961, green: 0.4352941176, blue: 0.9254901961, alpha: 1)
                let gradientlayer = CAGradientLayer()
                gradientlayer.name = "GradientLayerKey"
                gradientlayer.frame = CGRect(
                    x: 0,
                    y: 8,
                    width: sv.layer.frame.width,
                    height: sv.layer.frame.height-8
                )
                gradientlayer.cornerRadius = 18
                gradientlayer.colors = [one.cgColor, two.cgColor]
                gradientlayer.locations = [0, 1]
                gradientlayer.startPoint = CGPoint(x: 0.0, y: 0.0)
                gradientlayer.endPoint = CGPoint(x: 1.0, y: 1.0)
                sv.layer.insertSublayer(gradientlayer, at: 0)
            }
        }
    }
}

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    clearSelections()
    setSelection(item: item)
}
© www.soinside.com 2019 - 2024. All rights reserved.