In our last blog, we saw how to get started with SwiftUI. We saw how SwiftUI works and we also created a simple app with rendering text. Now let’s see how to render a list and a few things about navigation.
Rendering a List
TableView, TableViewController, TableViewCell all these complex things are out in SwiftUI 😜. You can simply map and display data like how it works in ReactNative.
Create a simple JSON
Create a JSON file to get data.
playerData.json
Create the Row View
The first view you’ll build in this tutorial is a row for displaying details about each player.
-
Create new SwiftUI named PlayerRow.swift
-
Add Player as stored data of PlayerRow.swift.
When you add the Player property, the preview stops working, because the PlayerRow type needs a player instance during initialization.
-
Now create a view and use Player property.
-
In PlayerRow_Previews, update it with Player data from playerData array.
PlayerRow.swift
Create the List of Players
In SwiftUI you can display a platform-specific list of views. Then create a new SwiftUI view, named **PlayerList.swift. **Replace default TextView with List and provide PlayerRow as an instance. We can loop player data with List.
PlayerList.swift
Navigating between screens
Now navigating between screens and passing data between views has become so simple.
Create a destination View
First, let’s create a Destination view of ContentViewType which I explained in my previous blog.
PlayerDetail.swift
Embed NavigationView and NavigationLink
Adding Navigation Capabilities to the List is done by embedding it in NavigationView and setting each row in a NavigationLink to set up a transition to destination view.
PlayerList.swift
You can add title for your View by calling navigationBarTitle function.
As player var is declared in PlayerDetail.swift you can pass data to PlayerDetail view by passing player data inside PlayerDetail() which is embedded in NavigationLink contructor in PlayerList.swift.
This is how List and Navigation work in SwiftUI Thanks for reading.
Happy coding :)
Cheers 🥂