UIKit玻璃按钮无法实现SwiftUI同款tint效果,如何正确设置?
在UIKit中为玻璃效果按钮设置着色(Tint)的正确方法
SwiftUI中可通过glassEffect(.regular.interactive().tint(.green))轻松实现带着色的玻璃按钮,效果如下:

但在UIKit中直接设置configuration.background.backgroundColor = .green会得到实心背景的按钮(如下所示),而非预期的玻璃着色效果:

解决方案
UIKit的玻璃按钮依赖UIVisualEffectView实现模糊效果,正确的着色方式是为模糊效果添加tint颜色,而非直接设置背景色。具体代码如下:
private let centerButton: UIButton = { let button = UIButton() button.setTitle("Tap Me", for: .normal) button.translatesAutoresizingMaskIntoConstraints = false var configuration = UIButton.Configuration.glass() // 创建带绿色tint的模糊效果(iOS 15+支持) var tintedBlurEffect = UIBlurEffect(style: .systemMaterial) if #available(iOS 15.0, *) { // intensity控制着色深浅,范围0-1,0为无着色,1接近实心 tintedBlurEffect = tintedBlurEffect.withTintColor(.green, intensity: 0.2) } configuration.background.effect = tintedBlurEffect // 调整前景色以适配tint,提升可读性 configuration.baseForegroundColor = .white button.configuration = configuration return button }()
原理说明
- UIKit玻璃按钮的默认背景是无tint的
UIBlurEffect,直接设置background.backgroundColor会覆盖模糊效果,导致实心背景。 - 通过
UIBlurEffect.withTintColor(_:intensity:)可以为模糊效果添加着色,既保留玻璃的透明模糊特性,又实现类似SwiftUI的tint效果。 intensity参数可控制着色的深浅,根据需求调整数值即可。
内容的提问来源于stack exchange,提问作者Farhandika Guenia
相关产品推荐
相关产品推荐

