How to change background color for tab in tvOS 13?

瘦欲@ 提交于 2019-12-08 13:41:38

After playing a bit with various properties of UITabBar and UITabBarController, I finally figured it out.

The property to change focused items background color is selectionIndicatorTintColor of UITabBarAppearance (documentation).

Since it is available on tvOS >= 13.0, you will have to wrap the assignment like this:

if #available(tvOS 13.0, *) {
    tabBar.standardAppearance.selectionIndicatorTintColor = .white
}

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

I accomplish this through a UITabBar extension. The view that is displayed on focus contains a UIMotionEffect so we check against that to find it.

@available(tvOS 13.0, *)
extension UITabBar {

    var focusBackgroundView: UIView? {
        let allSubviews: [UIView] = subviews.flatMap { [$0] + $0.subviews as [UIView] }
        return allSubviews.first{ !$0.motionEffects.isEmpty }
    }

}

Usage:

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