I’m working on building a simple page with a scroll view. The page includes a loading text with a small circular progress indicator, followed by a list of items. I want to manage the state of the view using an enum, which is a @Published variable in my viewModel.
enum MyState {
case dataFetched(data: [DataWrapper])
case loading
}
Then in my View Model I have this:
@Publised private(set) var viewState: MyState = .loading
My view is just a switch on that state that will decide what to show:
private var mainContentBuilder: some View {
Group {
switch viewModel.viewState {
case .loading:
EmptyView() // placeholder: replaced with my actual UI
case .dataFetched(let data):
EmptyView() //placeholder: replaced with my actual UI
}
}
}
What I want is to be able to independently update the UI components. For example, if I trigger a .loading
state after the initial list is populated, I want only the loading text to change while keeping the list of data intact. In my current setup, triggering a loading state causes the list to disappear.
I understand that this approach works if the view has only one main component, such as either a loading indicator or a list, but I want only part of the screen to be updated.
I also know that using multiple @Published
values makes this easy, but I’ve found that when there are multiple states, it becomes difficult to manage them all. That’s why I think using an enum might be a better alternative to have a single truth source.
How can I overcome this and redraw only parts of the screen and leave the rest intact with this enum approach?