SwiftUI 如何禁用 Button 和 NavigationLink 中的图像的覆盖颜色?

6 min read

对于 Button 和 NavigationLink 中的图像覆盖颜色,可以使用一个特殊的修饰符 .buttonStyle(PlainButtonStyle()),它会删除默认的图像覆盖颜色并保留原始图像。示例代码如下:

Button(action: {

}) {
    Image(systemName: "heart.fill")
}
.buttonStyle(PlainButtonStyle())
NavigationLink(destination: Text("Detail")) {
    Image(systemName: "chevron.left")
}
.buttonStyle(PlainButtonStyle())

如果需要设置自定义的 Button 或 NavigationLink 样式而不会影响图像颜色,可以创建一个遵循 ButtonStyleNavigationLinkStyle 协议的自定义样式。在自定义样式中,可以通过设置 foregroundColor 属性来控制文本和图像的颜色,而不会影响其覆盖颜色。下面是一个使用自定义 ButtonStyle 的示例代码:

struct CustomButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .foregroundColor(.white)
            .background(configuration.isPressed ? Color.red : Color.blue)
            .cornerRadius(10)
    }
}

Button(action: {

}) {
    Image(systemName: "heart.fill")
}
.buttonStyle(CustomButtonStyle())