簡體   English   中英

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

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

所以我有一些按鈕,我通過Interface Builder添加到視圖中,而不是使用我自定義的系統按鈕。 我試圖弄清楚如何改變特征,例如在不同狀態(突出顯示,聚焦等)期間的文本顏色和背景顏色。

我似乎不能通過IB做到這一點所以我可能會創建一個UIButton的子類並在那里更改它們,但是我很難找到要更改的屬性。 我沒有在文檔中明確提到它們

你肯定是在正確的軌道上!

一旦你didUpdateFocusInContext UIButton,就可以覆蓋函數didUpdateFocusInContext (來自UIFocusEnvironment協議,tvOS上的UIButton已經實現了)

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
    }
}

您還可以獲得幻想並轉換框架以模仿默認的“焦點”效果!

除了@Yoseob Lee的回答之外,您不需要創建UIButton子類來實現此目的。 只需確保在Interface Builder中為UIButton Type選擇custom ,然后覆蓋要更改按鈕屬性的類中的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()
    }
}

@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)
    }
}

注意===而不是==進行比較。 在大多數情況下,比較參考更快。 此外,將外觀的任何更改添加到動畫協調器組中都會更改為默認動畫(和時間),以便外觀更改看起來更像是tvOS默認行為的一部分。 此外,確保只將previouslyFocusedView恢復為默認狀態可以減少不必要的操作。

上述兩個答案都有效,但是對於這種簡單的更改,使用IB設置每個狀態的屬性會更容易。 雖然設置略微隱藏,但您確實可以更改文本顏色和背景顏色。

彈出以更改狀態配置

您可以使用以下方法在代碼中執行相同的操作:

[aButton setTitleColor:UIColor.greenColor forState:UIControlStateFocused];

斯威夫特3

swift 3.0中的一個實現:

override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {

    coordinator.addCoordinatedAnimations({
        if self.isFocused {
            self.button.alpha = 1.0 // in focus 
        }
        else {
            self.button.alpha = 0.0 // leaving focus
        }
        }, completion: nil)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM