In a recent tutorial we covered how to combine views and briefly touched on dynamic cells within a List. In this tutorial we’ll look more closely at how you can bring in dynamic content in to a List.
Create a new project and make sure you select SwiftUI when the option is presented.
Open up ContentView.swift and just below the import line at the top of the file, add the following struct:
struct Message: Identifiable {
var id = UUID()
var from: String
var date: String
var subject: String
var snippet: String
}
Here we define a struct and call it message. We also specify that it conforms to the Identifiable protocol. The protocol requires that we have an ID associated that is unique. We then declare the members of the struct, in this case four strings for a from, date, subject, and snippet.
We can take our Message SwiftUI view from yesterday and paste it in to the ContentView file just below the struct:
struct MessageRow: View {
var message: Message
var body: some View {
VStack(alignment: .leading) {
HStack {
Text(message.from)
.font(.title)
Spacer()
Text(message.date)
.font(.footnote)
}
Text(message.subject)
.font(.headline)
Text(message.snippet)
.font(.body)
}
.padding(10)
}
}
This defines what each row will look like. We first declare a message variable of type Message (ie, the struct we created just prior to this step).
We then layout what our cell looks like with a VStack, HStack, and a few Text views. For each Text view, we access the appropriate property such as the message.from which will identify who the message is from.
We then need to modify our ContentView struct as follows:
struct ContentView: View {
var body: some View {
let message1 = Message(from: "DevFright.com",
date: "3 Mar 2019 4:18am",
subject: "Weekly Newsletter",
snippet: "Welcome to this weeks newsletter...")
let message2 = Message(from: "James Smith",
date: "17 Mar 2019 5:57pm",
subject: "Re: Flight to NYC",
snippet: "Here are the flight details you requested...")
let message3 = Message(from: "Roger Podacter",
date: "30 March 2:00pm",
subject: "Re: Miami Dolphins",
snippet: "In speaking to Lois Einhorn...")
let messages = [message1, message2, message3]
return List (messages) { message in
MessageRow(message: message)
}
}
}
First we declare some constants, in this case each of them being created from Message. We initialise each one with the from, date, subject, and snippet. The ID was already previously assigned.
We then gather these together in to an array, and then we return a List of messages each from the messages array.
It is at this point that the Identifiable protocol set up at the beginning becomes important. If we omit to conform to that protocol in our Message struct we will get the following error:
Initializer 'init(_:rowContent:)' requires that 'Message' conform to 'Identifiable'
If you preview the app in the canvas, you will see three email messages, although they cannot be interacted with yet.
Leave a Reply
You must be logged in to post a comment.