在Swift(tvOS)中,您如何更改UIButton的高光和焦点颜色?

Pro*_*air 3 interface-builder uibutton swift tvos

所以我有一些按钮,我通过Interface Builder添加到视图中,而不是使用我自定义的系统按钮.我试图弄清楚如何改变特征,例如在不同状态(突出显示,聚焦等)期间的文本颜色和背景颜色.

我似乎不能通过IB做到这一点,所以我可能会创建一个UIButton的子类并在那里更改它们,但是我很难找到要更改的属性.我没有在文档中明确提到它们

Yos*_*Lee 6

你肯定是在正确的轨道上!

一旦你继承了UIButton,就可以覆盖这个函数didUpdateFocusInContext(来自UIFocusEnvironmentprotocol,UIButton在tvOS上已经实现了)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以获得幻想并转换框架以模仿默认的"焦点"效果!


Jim*_*med 5

除了 @Yoseob Lee 的答案之外,您不需要创建 UIButton 子类来实现此目的。只需确保custom在 Interface Builder 中选择 UIButton Type,然后重写didUpdateFocusInContext要更改按钮属性的类中的方法:

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)

    if context.nextFocusedView == myButton {
        myButton = UIColor.redColor()
    } else {
        myButton = UIColor.blueColor()
    }
}
Run Code Online (Sandbox Code Playgroud)


ski*_*kim 5

@Yoseob Lee是正确的,但他的回答缺少一些细节。这是一个稍微好一点的(主观)答案。

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    if context.nextFocusedView === self {
        coordinator.addCoordinatedAnimations({ 
            // change the appearance as desired
            }, completion: nil)
    } else if context.previouslyFocusedView === self {
        coordinator.addCoordinatedAnimations({ 
            // revert back to default appearance
            }, completion: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

注意===而不是==进行比较。在大多数情况下,比较参考更快。此外,将任何外观更改添加到动画协调器组更改为默认动画(和时间),以便外观更改看起来更像是 tvOS 默认行为的一部分。此外,确保仅将previouslyFocusedView恢复为默认状态可减少不必要的操作。