How to create list in SwiftUI

Just like a UITableView in UIKit It’s List in SwiftUI which is useful for creating the ListView in iOS Application.

SwiftUI-List-image

In This Tutorial we will be discussing about three type of List Creation in SwiftUI

1.Creating static list in SwiftUI

2. Create List with dynamic type 

1. Creating static list in SwiftUI

List { is type of struct in SwiftUI so let’s add

List {
    Text("iOS")
    Text("Android")
}

That’s all 🙂

2. Now Let’s create List with dynamic type in SwiftUI

Step 1: Create a Data Object who conforms to Identifiable protocol which is required for unique identity 

struct DeviceList: Identifiable {
    let id:Int
    let name: String
}

Step 2: Create @State var with list of object, this also could be the objects from webservice

@State var itemArray = [DeviceList(id: 1, name: "iPhone 6"),
                        DeviceList(id: 2, name: "iPhone 7"),
                        DeviceList(id: 3, name: "iPhone X")]

Step 3: Add it to the list by using of ForEach 

List {
    ForEach(itemArray) { itemObject in
        Text(itemObject.name)
    }
}

The Final code look like

struct ContentView: View {
    @State var itemArray = [DeviceList(id: 1, name: "iPhone 6"),
                            DeviceList(id: 2, name: "iPhone 7"),
                            DeviceList(id: 3, name: "iPhone X")]
    
    var subscriber: Cancellable? = nil
    
    var body: some View {
        NavigationView {
            // MARK:  Static List
            //            List {
            //                Text("iOS")
            //                Text("Android")
            //            }
            // MARK:  Dynamic List
            List {
                ForEach(itemArray) { itemObject in
                    Text(itemObject.name)
                }
            }
            .navigationTitle("List in SwiftUI")
        }
        
    }
}

You can also use ForEach with range like

List {
     ForEach((1...130), id: \.self) {
       Text("Index---> \($0)")
     }
}

Download Code Example for SwiftUI here

That’s all 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *