A SwiftUI List looks pretty similar to the Settings page in your iPhone. So, whenever you create a List in SwiftUI, that is how your lists will turn out by default.
Let’s create a custom SwiftUI List to add some creativity.
To begin, create a SwiftUI Xcode project, and create a struct
, namely, Data
.
struct Data: Identifiable {
let id = UUID()
var name: String
var age: Int
var gender: String
}
Let’s get back in our ContentView.swift
and populate some values into this struct
.
private let values: [Data] = [
Data(name: "John", age: 24, gender: "Male"),
Data(name: "Katherine", age: 25, gender: "Female"),
Data(name: "Jonas", age: 21, gender: "Male")
]
Now, inside your view, create a List, and use ForEach
to add and see all your data in list form.
var body: some View {
List {
ForEach(values){ item in
Text(item.name)
}
}
}
This is how your canvas will now look: This the default SwiftUI List, just like we saw for the Settings page.
Now, let’s create a custom List.
Create a new SwiftUI file, namely Design
.
Now create a RoundedRectangle
, with a cornerRadius
of 10.0
, and give it a blue
color. Also, embed the same in a ZStack, such that we can add our text on top of it later.
ZStack{
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.blue)
.frame(height: 100)
}
Text
and a few alignments
to make our list look prettier. ZStack(alignment: .leading){
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.blue)
.frame(height: 100)
VStack(alignment: .leading){
Text("John")
.foregroundColor(.white)
.font(.title)
Text("21")
.foregroundColor(.white)
.font(.title2)
Text("Male")
.foregroundColor(.white)
.font(.title2)
}
.padding()
}
.padding()
Content.swift
, replace your Text
and List
with the Design
file. var body: some View {
VStack {
ForEach(values){ item in
DesignView()
}
}
}
However, our canvas feels a little weird, because it does not show the actual value from the Data
. So, let’s parse some data into our view.
Back in our DesignView
, let’s create three variables, username
, age
, and gender
, and link up the values to the view.
struct DesignView: View {
@State var name: String
@State var age: Int
@State var gender: String
var body: some View {
ZStack(alignment: .leading){
RoundedRectangle(cornerRadius: 10.0)
.fill(Color.blue)
.frame(height: 100)
VStack(alignment: .leading){
Text(name)
.foregroundColor(.white)
.font(.title)
Text("\(age)")
.foregroundColor(.white)
.font(.title2)
Text(gender)
.foregroundColor(.white)
.font(.title2)
}
.padding()
}
.padding()
}
}
struct DesignView_Previews: PreviewProvider {
static var previews: some View {
DesignView(name: "John", age: 21, gender: "Male")
}
}
name
, age
, and gender
with the actual data value. VStack {
ForEach(values){ item in
DesignView(name: item.name, age: item.age, gender: item.gender)
}
}
That’s it! You can edit and style your custom list however you want; you can add a few images, symbols, colors, and whatnot to make your list look beautiful.