如何使 UIButton.Configuration 突出显示外观与系统按钮的外观匹配

How to make UIButton.Configuration highlight appearance match that of system buttons

提问人:Jordan H 提问时间:11/5/2023 最后编辑:Jordan H 更新时间:11/5/2023 访问量:45

问:

我正在对我的应用程序进行现代化改造并更新以使用 .我将系统按钮切换到默认的纯配置样式,但惊讶地发现按钮突出显示状态几乎不明显。当您点击传统的系统按钮时,它的 alpha 会减少很多以指示它正在被按下,因此很容易知道当您松开触摸时,此按钮将被触发。不幸的是,使用普通按钮配置时,很难看到突出显示状态,因为外观几乎没有变化。有没有办法使此突出显示的行为与所有其他按钮(例如 s)一样?UIButtonUIButton.ConfigurationUIBarButtonItem

let oldButton = UIButton(type: .system)
oldButton.setTitle("System Button", for: .normal)
oldButton.frame = CGRect(x: 50, y: 100, width: 150, height: 30)
view.addSubview(oldButton)

let newButton = UIButton(configuration: {
    var config = UIButton.Configuration.plain()
    config.title = "Plain Button"
    return config
}())
newButton.frame = CGRect(x: 50, y: 150, width: 150, height: 30)
view.addSubview(newButton)

这是系统按钮的突出显示状态:

enter image description here

这是普通按钮的突出显示状态:

enter image description here

iOS UIKit的 UIBuint

评论


答:

0赞 matt 11/5/2023 #1

这就是 a 的用途。有了它,您可以向运行时描述在按钮的特定状态下要执行的操作,例如当它突出显示时。例:titleTextAttributesTransformer

let newButton = UIButton(configuration: {
    var config = UIButton.Configuration.plain()
    config.title = "Plain Button"
    return config
}())
newButton.configuration?.titleTextAttributesTransformer = .init { 
    [unowned newButton] container in
    var newContainer = AttributeContainer()
    guard let baseColor = container.uiKit.foregroundColor else {
        return newContainer
    }
    switch newButton.state {
    case .highlighted:
        newContainer.foregroundColor = baseColor.withAlphaComponent(0.3)
    default:
        newContainer.foregroundColor = baseColor
    }
    return container.merging(newContainer)
}

随意调整“神奇数字”以适合您的口味。0.3

(这看起来可能很繁重,但如果你定义了一个基本按钮并从中派生了应用的所有其他按钮,则只需执行一次。在我们的应用程序中,我们定义了一整级联的按钮样式,这些按钮样式派生自基础。

评论

0赞 Jordan H 11/5/2023
这适用于标题,如果您有图像,还需要小心设置相同的 alpha。您是否有任何资源来学习如何从基础级联按钮标题?imageColorTransformer
0赞 Jordan H 11/5/2023
不过没有动画,除了试图让 alpha 正确之外,有没有办法让动画也匹配?它在触摸拖动退出/进入时有不同的时间。