I want to create a view where people can choose their preferred background image, these include a rectangle with a foreground colour or an image. So far I've got this to work by creating this
Struct:
struct BackgroundImage : Identifiable{
var background : AnyView
let id = UUID()
}
I am adding them to an array like so
ViewModel:
class VM : ObservableObject{
@Published var imageViews : Array<BackgroundImage> = Array<BackgroundImage>()
init(){
imageViews.append(BackgroundImage(background: AnyView(Rectangle().foregroundColor(Color.green))))
imageViews.append(BackgroundImage(background: AnyView(Rectangle().foregroundColor(Color.yellow))))
imageViews.append(BackgroundImage(background: AnyView(Image("Testimage"))))
}
which allows me to loop through an array of BackgroundImages like so
View:
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {
ForEach(VM.imageViews, id: \.self.id) { view in
ZStack{
view.background
//.resizable()
//.aspectRatio(contentMode: .fill)
.frame(width: g.size.width/2.25, height: g.size.height/8)
.clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
}
}
}
However I am unable to add
.resizable()
.aspectRatio(contentMode: .fill)
for the images as AnyView doesn't allow this.
Is there a better way of achieving this? Should I just have two separate arrays for Shapes/Images instead? Or is there an alternate View struct that would be better suited this?
Thanks!