Jean-Baptiste
Jean-Baptiste

Reputation: 967

Highlight SwiftUI Button programmatically

I've been trying to highlight programmatically a SwiftUI Button, without success so far…

Of course I could implement the whole thing again, but I'd really like to take advantage of what SwiftUI already offers. I would imagine that there is an environment or state variable that we can mutate, but I couldn't find any of those.

Here's a small example of what I would like to achieve:

struct ContentView: View {
    @State private var highlighted = false

    var body: some View {
        Button("My Button", action: doSomething())
            .highlighted($highlighted) // <-- ??

        Button("Toggle highlight") {
            highlighted.toggle()
        }
    }

   func doSomething() { ... }
}

It seems very odd that something so simple if not within easy reach in SwiftUI. Has anyone found a solution?

Upvotes: 1

Views: 2524

Answers (1)

Asperi
Asperi

Reputation: 257789

Here is a demo of possible approach, based on custom ButtonStyle. Tested with Xcode 11.4 / iOS 13.4

demo

struct HighlightButtonStyle: ButtonStyle {
    let highlighted: Bool

    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .background(highlighted || configuration.isPressed ? Color.yellow : Color.clear)
    }
}

extension Button {
    func highlighted(_ flag: Bool) -> some View {
        self.buttonStyle(HighlightButtonStyle(highlighted: flag))
    }
}

struct ContentView: View {
    @State private var highlighted = false

    var body: some View {
        VStack {
            Button("My Button", action: doSomething)
                .highlighted(highlighted)
            Divider()
            Button("Toggle highlight") {
                self.highlighted.toggle()
            }
        }
    }

   func doSomething() { }
}

Upvotes: 2

Related Questions