如何为 UIKit 中的 UIButton 设置 Liquid Glass 着色?
在 UIKit 中,给标准 UIButton 的 Liquid Glass 材质着色,优先使用 UIButton.Configuration.prominentGlass(),再通过按钮的 tintColor 指定颜色。configuration.background.backgroundColor 设置的是背景填色,不能代替玻璃材质着色。
如果需要直接控制 SwiftUI .regular.interactive().tint(.green) 对应的材质属性,可以使用 UIGlassEffect,设置它的 tintColor 和 isInteractive。
为什么设置背景色会像纯色按钮?
这行代码设置的是按钮背景颜色:
configuration.background.backgroundColor = .green
SwiftUI 的 .glassEffect(...tint(.green)) 则对玻璃材质着色。Liquid Glass 会根据下方内容调整颜色的亮度、饱和度等表现,因此效果与普通背景填充不同。Apple 的 Liquid Glass 介绍说明了这种着色机制。
标准 UIButton:使用 prominentGlass()
将原来的 .glass() 改为 .prominentGlass(),移除背景填色,再设置按钮的 tintColor:
import UIKit
@available(iOS 26.0, *)
private let centerButton: UIButton = {
var configuration = UIButton.Configuration.prominentGlass()
configuration.title = "Tap Me"
let button = UIButton(configuration: configuration)
button.tintColor = .green
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
Apple 在 WWDC25 的 UIKit 介绍中区分了这两种配置:
.glass():标准玻璃按钮。.prominentGlass():使用应用着色的突出玻璃按钮。
使用 .prominentGlass() 时,可以单独设置按钮的 tintColor 来指定颜色。仅在 .glass() 上设置 tintColor,并不能说明玻璃背景也会获得相同着色。
自定义材质:使用 UIGlassEffect.tintColor
题目中的 SwiftUI 代码直接配置了玻璃材质。在 UIKit 中,如果也需要明确指定 .regular、交互行为和材质颜色,可以这样创建效果:
let glassEffect = UIGlassEffect(style: .regular)
glassEffect.tintColor = .green
glassEffect.isInteractive = true
let glassView = UIVisualEffectView(effect: glassEffect)
| SwiftUI | UIKit |
|---|---|
.regular |
UIGlassEffect(style: .regular) |
.tint(.green) |
glassEffect.tintColor = .green |
.interactive() |
glassEffect.isInteractive = true |
glassView 是玻璃容器。需要在其中放置按钮时,可以将使用 .plain() 配置的 UIButton 添加到 glassView.contentView,再设置布局约束,避免叠加另一层玻璃按钮背景。Apple 的自定义玻璃示例也使用了 UIGlassEffect 和 UIVisualEffectView。
glassEffect.tintColor 控制材质着色,button.tintColor 控制按钮在当前样式下使用的着色。这两个属性属于不同对象。
外观对比时的注意事项
上述 Liquid Glass API 需要 iOS 26 或更高版本,并使用包含这些 API 的 SDK 编译。如果还要支持旧系统,需要添加可用性判断和回退样式。
对比 SwiftUI 与 UIKit 的外观时,应使用相同的背景内容和明暗模式。Liquid Glass 会适应下方内容,“降低透明度”等辅助功能设置也会改变它的外观。Apple 对辅助功能适配的说明解释了这些变化。
.prominentGlass() 是系统按钮样式,不能保证与自定义 SwiftUI ButtonStyle 逐像素一致。如果需要控制题目中的那组材质属性,应使用 UIGlassEffect 自定义组合。
备注:内容仅供参考。
