簡體   English   中英

在 UIButton 中應用 Plain 樣式時如何禁用標題高亮顏色?

[英]How to disable title highlight color when apply Plain style in UIButton?

我讀過這個並嘗試將類型更改為自定義,當我以舊方式配置按鈕時它有效(按鈕的樣式是默認的),但是當我應用從 iOS 15 引入的普通樣式時我可以注意到顏色改變了,是嗎禁用它的方法? 我也嘗試過adjustsImageWhenHighlightedshowsTouchWhenHighlighted但它們也不起作用。 在此處輸入圖像描述

您可以通過配置的.titleTextAttributesTransformer執行此操作。

如果您在 Storyboard 中添加了一個 Plain 樣式按鈕,並且您希望標題為 - 例如 - .systemRed且 state沒有變化,您可以這樣做:

    var config = storyboardButton.configuration
    
    // use only .systemRed for title color (in all states)
    config?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
        var outgoing = incoming
        outgoing.foregroundColor = UIColor.systemRed
        return outgoing
    }
    
    storyboardButton.configuration = config
    

代碼創建按鈕的類似方法:

    var cfg = UIButton.Configuration.plain()

    // use only .systemGreen for title color (in all states)
    cfg.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
        var outgoing = incoming
        outgoing.foregroundColor = UIColor.systemGreen
        return outgoing
    }
    
    cfg.title = "Code Button"

    let codeButton = UIButton()
    codeButton.configuration = cfg

為了更靈活,您可以像這樣對UIButton進行子類化:

class CustomHighlightButton: UIButton {
    
    var normalColor: UIColor = .systemRed
    var highlightColor: UIColor = .systemGreen
    
    override func updateConfiguration() {
        guard let cfg = configuration else {
            return
        }
        
        var updatedCfg = cfg
        
        let newTitleColor: UIColor
        
        switch self.state {
        case .highlighted:
            newTitleColor = highlightColor
        default:
            newTitleColor = normalColor
        }
        
        updatedCfg.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
            var i = incoming
            i.foregroundColor = newTitleColor
            return i
        }
        
        self.configuration = updatedCfg
    }
}

然后像這樣實現它:

    let customButton = CustomHighlightButton()
    var cfg = UIButton.Configuration.plain()
    cfg.title = "Custom Highlight Button"
    customButton.configuration = cfg

    // use only .systemBlue for title color (in all states)
    customButton.normalColor = .systemBlue
    customButton.highlightColor = .systemBlue

要么:

    // use .systemBlue for title color - highlighted state
    customButton.highlightColor = .systemBlue
    // use .systemRed for title color - all other states
    customButton.normalColor = .systemRed

暫無
暫無

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

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