SwiftUI按钮:移除强调色且保留功能及默认动画方案咨询
解决SwiftUI按钮图标颜色与动画保留问题
问题解决方案
要同时保留按钮的默认点击动画、完整功能,且让applelogo显示预期颜色,有两种简洁可行的方式:
方式一:自定义ButtonStyle(推荐)
通过自定义按钮样式模拟默认按压动画,同时避免按钮tint对图标颜色的覆盖:
// 自定义按钮样式,还原默认按压的透明度+缩放动画 struct CustomAppleButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .opacity(configuration.isPressed ? 0.7 : 1.0) .scaleEffect(configuration.isPressed ? 0.95 : 1.0) .animation(.easeInOut(duration: 0.1), value: configuration.isPressed) } } // 使用自定义样式的按钮 Button{ print("hi") } label:{ Image(systemName: "applelogo") .frame(maxWidth: .infinity) .padding() .background(.clear) .cornerRadius(15) .overlay( RoundedRectangle(cornerRadius: 20) .stroke(.gray, lineWidth: 2) ) } .buttonStyle(CustomAppleButtonStyle())
方式二:锁定图标前景色
如果只需让图标跟随系统主色(适配深浅模式),直接给Image添加前景色修饰即可,无需修改按钮样式:
Button{ print("hi") } label:{ Image(systemName: "applelogo") .foregroundColor(.primary) // 强制使用系统主色,不受按钮tint影响 .frame(maxWidth: .infinity) .padding() .background(.clear) .cornerRadius(15) .overlay( RoundedRectangle(cornerRadius: 20) .stroke(.gray, lineWidth: 2) ) }
为什么renderingMode(.original)无效?
renderingMode(.original)的作用是让图片保留自身携带的原始色彩信息,这个逻辑仅对带有多色数据的图片生效(比如自定义导入的多色PNG、SVG)。而applelogo属于SF Symbols中的单色模板图标,它本身只有形状路径,没有固定颜色数据,显示颜色完全由按钮的tint或视图的foregroundColor控制,因此这个修饰符对它不会产生任何效果。
内容的提问来源于stack exchange,提问作者Tay Baye
相关产品推荐
相关产品推荐

