SwiftUI + MVVM: Movie Booking App (Part 1)

Tram Ho

This is part 1 of the Building a movie ticketing app series. In this article, I will create the main screen that displays the Watch movies collection.


Create a model

Things need to notice:

  1. Create struct “MovieBundle” to decode data.
  2. Then create a “Movie” protocol, you will see why in Part 2 of this series.


Create ViewModel

Here is a brief summary of the above code:

1. We create the HomeSection enum that will be used as the key to retrieve specific parts from the model.

2. Then, in the ViewModel, we read the file containing the data, decode it, and set the published property to notify interested views so they can reload and reflect the current state of the tissue. Figure.


We will use UIKit’s UICollectionView and UICollectionViewCompositionalLayout. Create a file with the name MovieCollectionView.swift.

Add this code inside that struct:!

The first method is where we will initialize any view we want to use in SwiftUI, in this case, it’s a UICollectionView . Let makeUIView method be init (frame: CGRect) in normal UIKit UIView.

The second view is where you usually update the view you want to use in SwiftUI.There are two other methods, the first one is makeCoordinator () which we will learn more shortly and the last one. The same is called dismantleUIView(uiView: Self.UIViewType, coordinator: Self.Coordinator) is used when this view is about to be killed and wants to clean up resources to avoid leaks memory, etc.


The coordinator will be the class that coordinates, the interaction between SwiftUI and whatever UIView we are using. This is the class that will handle all data source and delegate.

Add the following class in the same structure, below updateUIView :

We also keep a reference to the parent structure, MovieCollectionView

In the same class, add the following method:

We return the standard FlowLayout now, but we will change with UICollectionViewCompositableLayout later.

Now add the following method to MovieCollectionView.swift above the dispatcher class:

This is the fourth method from the UIViewRepftimeable protocol. Its only job is to initialize a new Coordinator instance that we will use shortly.

After you do that, add the following in the makeUIView method:

A few things to note in the above code:

  1. We retrieve the coordinator from the context in turn allowing us to access everything in the dispatcher class.
  2. We set the data and authorize the coordinator because the coordinator follows those two protocols.

Before moving on, we need to create UICollectionView cells for each section.

Share the news now

Source : Viblo