Search code examples
swiftuikituibuttonattributedstring

How to get attribute from AttributeContainer in UIKit and assign it to some variable


I create next subclass:

import UIKit

class Button: UIButton {

    override func updateConfiguration() {
        var config = configuration ?? UIButton.Configuration.plain()

        let color = config.attributedTitle?.foregroundColor

        switch state {
        case .normal:
            config.attributedTitle?.foregroundColor = color.withAlphaComponent(1)

        case .highlighted:
            config.attributedTitle?.foregroundColor = color.withAlphaComponent(0.5)

        default:
            break
        }

        configuration = config
    }
}


I this class I want to get foregroundColor from attributedTittle(AttributedString class) to assign it later with alphaComponent to different button states, BUT I can't get any attribute from attributedString(or AttributedContainer) in updateConfiguration method.
In my example property "color" is always nil (actually all other attribute are nil if I try get them) and the return type of "color" is:

AttributeScopes.SwiftUIAttributes.ForegroundColorAttribute.Value?

And I get this error when try to assign color back to attributedString:

 Value of type 'AttributeScopes.SwiftUIAttributes.ForegroundColorAttribute.Value?' (aka 'Optional<Color>') has no member 'withAlphaComponent'

So why I can't get any attributes from AttributedString here?


Solution

  • It appears that the compiler is prioritising the foregroundColor in the SwiftUIAttributes attribute scope. You can force it to choose the UIKit one by specifying the type of color.

    let color: UIColor? = config.attributedTitle?.foregroundColor
    

    Alternatively, access the uiKit attribute scope directly:

    let color = config.attributedTitle?.uiKit.foregroundColor
    

    Note that this should be an optional type, so you should unwrap it when you use withAlphaComponent:

    config.attributedTitle?.foregroundColor = color?.withAlphaComponent(1)
                                                   ^