Search code examples
swiftuikituibutton

How do you change (by .configuration?) the tintColor, when the button is depressed, in a custom/filled UIButton?


Pls note that this question is about tintColor. This question has no relation to backgroundColor, which is totally different. Also, I notice there are many QA about the tintColor of an image on a button. This has nothing to do with that. This a question is about the property .tintColor of a UIButton

Have a typical (modern-day) button,

private lazy var toggle: UIButton = {
    let v = UIButton(type: .custom)
    v.configuration = .filled()
    v.configuration?.titleTextAttributesTransformer =
    UIConfigurationTextAttributesTransformer { i in
        var o = i
        o.font = UIFont.monospacedSystemFont(ofSize: 12, weight: .medium)
        return o
    }
    v.layer.cornerRadius = 5
    v.layer.cornerCurve = .continuous
    v.layer.borderWidth = 1
    v.layer.borderColor = UIColor.systemYellow.cgColor
    v.clipsToBounds = true
    v.setTitle("Log", for: [])
    v.setTitleColor(.systemGray3, for: [])
    v.tintColor = .systemGray
    ...

Note that the tintColor is system gray.

How the heck do you set the color to which the tintColor changes, when the button is depressed?

To express that better: how do you (ideally using configuration) make the tintColor change to some other specified color when the state changes?


Solution

  • Ok so it turns out you are not talking about the tint color at all. You're talking about the background color.

    Set the configuration's background.backgroundColor to a fixed color, and it will stay fixed.

    For more flexibility (eg a different color while pressing), set instead the configuration's background.backgroundColorTransformer.