Skip to content
Tamerlan Satualdypov edited this page Aug 1, 2023 · 1 revision

The View layer contains entities that provides user interaction and handles presentation logic. It defines the UI of an application, handles user interaction and reacts on changes of the data.

Designing your View

The entities in the View layer are responsible for all presentation and presentation logic in your app. Thanks to the framework the binding to the Model is performed by only using @State property wrapper and reaction on change is processed automatically by the SwiftUI. Therefore, the work that was previously done by ViewController or ViewModel is now eliminated by the framework. You could also use the composable nature of the SwiftUI's View and divide your entity into smaller parts for better maintainability. To facilitate the sharing of state/model between multiple Views, the use of @EnvironmentObject is recommended.

Examples

Simple View
struct PostList: View {
    @State private var posts: [Post] = []

    var body: some View {
        List(...) {
            ...
        }
        .task {
            self.posts = await Post.all
        }
    }
}
Complex View
struct PostList: View {
    @StateObject private var store: PostStore = .init()

    var body: some View {
        VStack {
            AllPostSection()
            Divider()
            LikedPostSection()
        }
        .environmentObject(self.store)
        .task {
            await self.store.load()
        }
    }
}

struct AllPostSection: View {
    @EnvironmentObject private var store: PostStore

    var body: some View {
        ...
    }
}

struct LikedPostSection: View {
    @EnvironmentObject private var store: PostStore

    var body: some View {
        ...
    }
}
Clone this wiki locally