swiftui

Button with accent color and vibrancy


Is it possible to create a button with vibrancy AND foreground accent color, using SwiftUI on MacOS?

This is my code:

    Button(action: {
        self.onClick()
    }, label: {
        Label(self.title, systemImage: "gearshape.circle.fill")
            .foregroundStyle(Color.accentColor)
    })
    .buttonStyle(.plain)
    .labelStyle(.iconOnly)

I want this button to have vibrancy when placed over material background. According to the manual ( https://developer.apple.com/documentation/swiftui/view/foregroundstyle(_:) ) foregroundStyle() disables vibrancy unless used with hierarchical styles. But it is also the only way I can use to set the button to accent color, isn't it? Is there a way to make button icon in accent color AND keep its vibrancy? Eg. labels in SplitView sidebar seem to have this effect.


Solution

  • I think the term vibrancy in this context is a vague term to describe added contrast.

    You might be able to achieve something similar by applying some kind of .blendMode. For example:

    Button(action: onClick) {
        Label("Settings", systemImage: "gearshape.circle.fill")
            .foregroundStyle(Color.accentColor)
            .blendMode(.screen) // 👈 here
    }
    .buttonStyle(.plain)
    .labelStyle(.iconOnly)
    

    Ps. For a description of how the blend modes work, the documentation for GraphicsContext.BlendMode is a lot more useful than what you will find under BlendMode.