1

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?

Petr Bones
  • 11
  • 3
  • What do you mean by you "can't" get any attribute? What did the code do and what did you expect? Can you show a [mcve]? Also, I don't think you should mix `setAttributedTitle` with the configuration APIs. – Sweeper Jul 08 '23 at 08:00
  • @Sweeper I change my code, so you can understand what i expect. About mixing it, I think it doest not matter, because config.attributedString still have all attribute which I assigned with `setAttributedTitle `. I also try to assign my custom `AttributedString` to `configuration.attributedString` and still have same errors. – Petr Bones Jul 08 '23 at 08:31

1 Answers1

0

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)
                                               ^
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Thank you!! It works. Btw, I tried `let color = config.attributedTitle?.foregroundColor as? UIColor`, but it doesn't work, so I was confused. – Petr Bones Jul 08 '23 at 11:21