代码之家  ›  专栏  ›  技术社区  ›  Petr Bones

如何从UIKit中的AttributeContainer中获取属性并将其分配给某个变量

  •  0
  • Petr Bones  · 技术社区  · 2 年前

    我创建下一个子类:

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

    在这个类中,我想从attributedTitle(AttributedString类)中获取foregroundColor,以便稍后使用alphaComponent将其分配给不同的按钮状态,但在updateConfiguration方法中,我无法从attributeString(或AttributedContainer)中获取任何属性。
    在我的示例中,属性“color”始终为nil(实际上,如果我尝试获取其他属性,则所有其他属性都为nil),并且“color”的返回类型为:

    AttributeScopes.SwiftUIAttributes.ForegroundColorAttribute.Value?
    

    当我试图将颜色重新分配给attributedString时,我会收到这个错误:

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

    那么,为什么我不能在这里从AttributedString获取任何属性呢?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Sweeper    2 年前

    看来编译器正在优先考虑 foregroundColor 在中 SwiftUIAttributes 属性范围。您可以通过指定的类型来强制它选择UIKit color .

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

    或者,访问 uiKit 直接属性范围:

    let color = config.attributedTitle?.uiKit.foregroundColor
    

    请注意,这应该是一个可选类型,因此在使用时应该打开它 withAlphaComponent :

    config.attributedTitle?.foregroundColor = color?.withAlphaComponent(1)
                                                   ^
    
    推荐文章