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?
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())
}
}
}
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)
}
}
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With