Search code examples
swiftuibuttoninterface-buildertvos

In Swift (tvOS) how do you change a UIButton's highlight and focus colors?


So I have some buttons that I've added to a view through the Interface Builder and rather than using the system buttons I made them custom. I'm trying to figure out how to change characteristics, such as the text color and background color during different states (highlighted, focused, etc).

It doesn't seem like I can do it through the IB so I'll probably make a subclass of UIButton and change them there, but I'm having trouble finding what properties to change. I don't see them explicitly mentioned in the documentation


Solution

  • You're definitely on the right track!

    Once you subclass UIButton, you can override the function didUpdateFocusInContext (from UIFocusEnvironment protocol, which UIButton on tvOS already implements)

    override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
        super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)
    
        if context.nextFocusedView == self {
            // This is when the button will be focused
            // You can change the backgroundColor and textColor here
        } else {
            // This is when the focus has left and goes back to default
            // Don't forget to reset the values
        }
    }
    

    You can also get fancy and transform the frame to imitate the default "focus" effect!