Nicolas
Nicolas

Reputation: 279

SwiftUI conditional .buttonStyle

I am trying to change the style of a button based on a condition like this:

.buttonStyle((selection == index) ? .borderedProminent : .bordered)

Strangely it throws this error:

Type 'ButtonStyle' has no member 'borderedProminent'

I suppose I am making a syntax mistake?

Upvotes: 19

Views: 2215

Answers (2)

Henadzi Rabkin
Henadzi Rabkin

Reputation: 7063

As @asperi noted this solution works perfectly https://stackoverflow.com/a/64769260/12299030

....     
     Button {
        selected = badge
     } label: {
        Text(badge)
     }.tagStyle(selected == badge ? TagButtonStyle.prominent : TagButtonStyle.bordered)

....


    enum TagButtonStyle {
        case prominent
        case bordered
    }
    
    extension Button {
        
        @ViewBuilder
        func tagStyle(_ style: TagButtonStyle) -> some View {
            switch style {
            case .prominent:
                self.buttonStyle(BorderedProminentButtonStyle())
            case .bordered:
                self.buttonStyle(BorderedButtonStyle())
            }
        }
    }

Upvotes: 3

Andy Jazz
Andy Jazz

Reputation: 58563

Your ternary operator ? : doesn't work because all 5 button styles, that currently available in SwiftUI, are of different types. Thus, you have to use some keyword that allows you to define an opaque parameter and return a needed type. As you can see, I've implemented some keyword not only for method's return type here but also for its parameter.

Here's my code:

import SwiftUI

struct ContentView : View {
    @State var sentence = ""
    var selection = 0
    var index = 1
    let prominent = BorderedProminentButtonStyle()
    let bordered = BorderedButtonStyle()
    
    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()            
            VStack {
                Text(sentence).foregroundStyle(.white)
                
                if (selection == index) { createButton(prominent) } 
                else { createButton(bordered) }
            }
        }
    }
    func createButton(_ prim: some PrimitiveButtonStyle) -> some View {
        ZStack {
            Button("Check an Equality") {
                if (selection != index) {
                    sentence = "Selection isn't equal to Index"
                } else {
                    sentence = "Equality"
                }
            }
            .buttonStyle(prim)
        }
    }
}

enter image description here

Upvotes: 1

Related Questions