Matriz que incluye múltiples tipos de vista en Swift / SwiftUI

Aug 18 2020

Quiero crear una vista en la que las personas puedan elegir su imagen de fondo preferida, que incluyen un rectángulo con un color de primer plano o una imagen. Hasta ahora he conseguido que esto funcione creando esto

Estructura:

struct BackgroundImage : Identifiable{
var background : AnyView
let id = UUID()
}

Los estoy agregando a una matriz así

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"))))
    }

lo que me permite recorrer una matriz de BackgroundImages como tal

Ver:

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

Sin embargo, no puedo agregar

 .resizable()
 .aspectRatio(contentMode: .fill)

para las imágenes ya que AnyView no lo permite.

¿Existe una mejor manera de lograrlo? ¿Debería tener dos matrices separadas para formas / imágenes? ¿O hay una estructura de Vista alternativa que se adaptaría mejor a esto?

¡Gracias!

Respuestas

1 vacawama Aug 18 2020 at 19:51

Como mencionó @ DávidPásztor en los comentarios, es un mal diseño almacenar Vistas en su ViewModel.

Realmente solo necesitas almacenar un color y un nombre de imagen. Deje que el código de construcción de vistas construya las vistas reales.

Aquí hay una posible implementación.

struct BackgroundItem: Identifiable {
    private let uicolor: UIColor?
    private let imageName: String?
    let id = UUID()
    
    var isImage: Bool { imageName != nil }
    var color: UIColor { uicolor ?? .white }
    var name: String { imageName ?? "" }
    
    init(name: String? = nil, color: UIColor? = nil) {
        imageName = name
        uicolor = color
    }
}

class VM : ObservableObject{
    @Published var imageItems: [BackgroundItem] = []
        
    init() {
        imageItems = [.init(color: .green),
                      .init(color: .blue),
                      .init(name: "TestImage")]
    }
}

struct ContentView: View {
    @ObservedObject var vm = VM()

    var body: some View {
        GeometryReader { g in
            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())]) {
                ForEach(vm.imageItems) { item in
                    ZStack{
                        if item.isImage {
                            Image(item.name)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                        } else {
                            Color(item.color)
                        }
                    }
                    .frame(width: g.size.width/2.25, height: g.size.height/8)
                    .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)
                }
            }
        }
    }
}

Nota: Pensé en usar an enumpara almacenar la distinción entre imageName y color, pero fue más simple usar opcionales y almacenar el que necesitaba. Con la interfaz que está expuesta al código de construcción de vistas, puede cambiar fácilmente la implementación a la forma en que desee almacenar la información.