Home > database >  SwiftUI Switch statement
SwiftUI Switch statement

Time:07-25

How can I present in swiftUI a view in a switch case? This is my code and I would like instead of return "home" to return HomeView().

import Foundation

enum SideMenuViewModel: Int, CaseIterable, Decodable {
    case Home
    case Users
    case TODOs
    case AboutUs
    
    var title: String {
        switch self {
        case .Home: return "Home"
        case .Users: return "Users"
        case .TODOs: return "TODOs"
        case .AboutUs: return "AboutUs"
        }
    
    }
    var imageName: String {
        switch self {
        case .Home: return "bookmark.circle"
        case .Users: return "person"
        case .TODOs: return "list.bullet"
        case .AboutUs: return "info.circle"
        }
    }
}

CodePudding user response:

You need view builder property, like

@ViewBuilder var view: some View {
    switch self {
    case .Home:
       HomeView()
    case .Users:
       UsersView()
    case .TODOs:
       TODOView()
    case .AboutUs:
       AboutUsView()
    }
}

CodePudding user response:

Instead of trying to return a View from an enum, inject the enum into your View and switch over the enum inside the view, then return the appropriate View from there.

A ViewModel should be independent from its view type, only the view should know about the VM, not the other way around.

struct SideMenuView: View {
  private let viewModel: SideMenuViewModel

  init(viewModel: SideMenuViewModel) {
    self.viewModel = viewModel
  }

  var body: some View {
    switch viewModel {
    case .AboutUs:
      return AboutUsView(...)
    case .Home:
      return HomeView(...)
      ...
    }
  }
}
  • Related