Search code examples
uitabbarcontrolleruitabbartvosuitabbaritemtvos13

How to change background color for tab in tvOS 13?


enter image description hereTvOS 13. I have a UITabBarController with tabs. And can customize almost everything except this obvious thing: focused tab's background. It's always white. Guide tells

Specify tints for selected and unselected items

I tried:

view.backgroundColor = .purple
tabBar.tintColor = .yellow
tabBar.barTintColor = .red
tabBar.unselectedItemTintColor = .brown
tabBar.backgroundColor = .green
tabBar.backgroundImage = UIColor.blue.toImage()
tabBar.shadowImage = UIColor.orange.toImage()
tabBar.selectionIndicatorImage = UIColor.burgundy.toImage()

Nothing helped.


Solution

  • For @davidv and other folks, here is my solution:

    extension UIView {
        func subviews<T:UIView>(ofType type: T.Type) -> [T] {
            var result = self.subviews.compactMap { $0 as? T }
            for sub in self.subviews {
                result.append(contentsOf: sub.subviews(ofType: type))
            }
            return result
        }
    }
    
    extension UIViewController {
        override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
            // перекраска кнопки
            let allSubviews = tabBar.subviews(ofType: UIView.self)
            let whiteSubviews = allSubviews.filter { $0.backgroundColor == .white }
            for s in whiteSubviews {
                s.backgroundColor = .gold
            }
        }
    }
    

    UPDATE:

    For coloring text:

    item.setTitleTextAttributes([NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: colorSelected], for: [.focused])
    item.setTitleTextAttributes([NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: colorSelected], for: [.highlighted])
    item.setTitleTextAttributes([NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: colorUnselected], for: [.normal])
    

    For coloring background:

    tabBar.standardAppearance.selectionIndicatorTintColor = .gold