How to change background color for tab in tvOS 13?

≡放荡痞女 提交于 2020-01-14 03:37:21

问题


TvOS 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.


回答1:


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
}



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/58320307/how-to-change-background-color-for-tab-in-tvos-13

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