我创建下一个子类:

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?

在try 将 colored颜色 重新分配给属性字符串时,我收到以下错误:

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

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

推荐答案

编译器似乎正在优先考虑SwiftUIAttributes属性作用域中的foregroundColor.您可以通过指定类型color来强制它 Select UIKit One.

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

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

let color = config.attributedTitle?.uiKit.foregroundColor

请注意,这应该是一个可选类型,因此在使用withAlphaComponent时应将其解包:

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

Swift相关问答推荐

UITableView未显示类数组数据

为什么第二项任务不在第一项任务完成之前开始?(并发队列)

当计数大于索引时,索引超出范围崩溃

找出touch 点的屏幕亮度

当将新值推送到 NavigationStack 时,SwiftUI 的 navigationDestination 已在堆栈的早期声明

为什么 XUIView 中的 Binding 看不到更新后的值?

如何在 swift 5.0 中获取当前行

如何在不将变量转换为字符串的情况下判断变量在 Swift 中是否为 Optional(nil)?

我如何遵守与演员的协议?

LeetCode 249. 分组移位字符串

如何更改 Picker 的边框 colored颜色

在 Swift 中实现自定义异步序列

.onTapGesture 不适用于 Stepper,仅适用于其文本

swift 3 错误:参数标签 '(_:)' 不匹配任何可用的重载

Swift:如何从函数返回类类型

无法推断泛型参数的参数

自定义 MKAnnotation 标注视图?

使用 Swift 以编程方式自定义 UITableViewCell

swift中的匿名类

滑动侧边栏菜单 IOS 8 Swift