How to: Use conditional custom background views for background modifier?

Viewed 618

Usually it ist straight forward how to use the ternary oparator for conditional changes in a modifier. But when I'm trying to switch between two custom views for the background modifier I get this error. This ist not the case if you e.g. directly specify colors as alternate views.

Error: Result values in '? :' expression have mismatching types 'BackgroundView1' and 'BackgroundView2'

import SwiftUI

struct TestView: View {

@State var buttonPressed = false

var body: some View {

    Button(action: {self.buttonPressed.toggle()}) {

        Image(systemName: "circle.fill")
            .background(self.buttonPressed ? BackgroundView1() : BackgroundView2()) // Error
//                .background(buttonPressed ? Color.red : Color.green)
    }

}
}

struct BackgroundView1: View {

var body: some View {

    Color.red

    }
}

struct BackgroundView2: View {

var body: some View {

    Color.green

}
}

struct TestView_Previews: PreviewProvider {
static var previews: some View {
    TestView()
}
}
1 Answers

View must be one type, here is possible solution

Image(systemName: "circle.fill")
    .background(Group {
       if self.buttonPressed { BackgroundView1() }
         else { BackgroundView2() }
    }) 

alternate is, if views are simple (otherwise it might be performance issue),

    Image(systemName: "circle.fill")
        .background(self.buttonPressed ? AnyView(BackgroundView1()) : AnyView(BackgroundView2()))
Related