Home > OS >  How to disable title highlight color when apply Plain style in UIButton?
How to disable title highlight color when apply Plain style in UIButton?

Time:12-06

I have read enter image description here

CodePudding user response:

You can do this via the configuration's .titleTextAttributesTransformer.

If you have added a Plain style button in Storyboard, and you want the title to be - for example - .systemRed with NO change for state, you can do this:

    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
    

Similar approach for code-created button:

    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

For more flexibility, you can subclass UIButton like this:

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

Then implement it like this:

    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

or:

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