Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Color and BackgroundStyle in SwiftUI

Tags:

swift

swiftui

I'm trying to do this where a background modifier could either accept an optional BackgroundStyle or a Color.

struct ContentView: View {
    var background: BackgroundStyle?
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .background(background ?? Color.gray)
        .padding()
    }
}

#Preview {
    ContentView(background: .background)
}

I get this error and I'm not sure how to resolve it.

Cannot convert value of type 'Color' to expected argument type 'BackgroundStyle'

like image 967
Berry Blue Avatar asked Dec 29 '25 06:12

Berry Blue


1 Answers

You can use AnyShapeStyle to erase the types, converting both Color and BackgroundStyle to AnyShapeStyle.

.background(background.map(AnyShapeStyle.init) ?? AnyShapeStyle(Color.gray))

The optional here makes this a bit messy. I would use a Bool instead, to indicate whether to use the background style. There is only one instance of BackgroundStyle, anyway.

let useDefaultBackground: Bool

...

.background(
    useDefaultBackground ? AnyShapeStyle(.background) : AnyShapeStyle(Color.gray)
)
like image 81
Sweeper Avatar answered Dec 30 '25 22:12

Sweeper



Donate For Us

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