UITabBarItems not showing up after subclassing UITabBarController

丶灬走出姿态 提交于 2019-12-23 05:17:57

问题


I've been trying to add a gradient to the UITabBar in my app. After a few failed attempts I followed the steps from this question and the. gradient now works, but the UITabBarItems are invisible (although they all work). How can I make sure that both the gradient and the UIITabBarItems are visible?

class GradientTabBarController: UITabBarController {

let layerGradient = CAGradientLayer()

override func viewDidLoad() {
    super.viewDidLoad()
    print("custom tabbar loaded")
    layerGradient.colors = [UIColor(named: "tabBarGradient1")?.cgColor, UIColor(named: "tabBarGradient2")?.cgColor]
    layerGradient.startPoint = CGPoint(x:0.5, y: 0)
    layerGradient.endPoint = CGPoint(x: 0.5, y: 1)
    layerGradient.frame = tabBar.bounds
    self.tabBar.layer.addSublayer(layerGradient)
 } 
}

what it looks like in the simulator:

The missing Icons (view from Interface Builder)


回答1:


What you're doing is not supported. However, if you're going to do it, you need to put the gradient layer behind the tab bar items. You are putting it in front of the tab bar items:

 self.tabBar.layer.addSublayer(layerGradient)

You need to say something more like:

 self.tabBar.layer.insertSublayer(layerGradient, at:0)

The idea is to put the layer behind the tab bar items. But exactly what number to use, I'm not sure; you'll have to experiment, and I don't guarantee the robustness of any such action going forward. And it might not even work at all, because the tab bar items are not views.

The correct way to make a custom background for a tab bar is to make a UIView displaying your gradient, and set it as the tab bar's backgroundImage. Why don't you do this the correct supported way instead of your hacky unsupported way? You should use the framework, not fight the framework.



来源:https://stackoverflow.com/questions/48853864/uitabbaritems-not-showing-up-after-subclassing-uitabbarcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!