Table with Dynamic Cell in SwiftUI

In previous Post I demonstrated the ways we can have a Table in SwiftUI.
Now lets get started to a simple demo where we can load dynamic info in table cell.


I am creating a snippet where I want to load Roll Number and Name of students of a class in Table.
For this I used List which will create rows equal to rollNosArray count (i.e. 4 for now).

1. Lets have two arrays, first for names and the other for roll numbers.
2. Iterate List through the rollNosArray, so we will have 4 rows/cells.
3. Now create a new Struct named DynamicCell. This is our custom dynamic cell.
4. As per my need I wanted Two Labels to display info inside a row horizontally.
5. So I took a HStack and inside it added two Text.
6. For a clear separation between two Text's I added a Divider. 
7. Back to our ContentView Struct, inside List call this DynamicCell and pass the value to the two variables declared in DynamicCell Struct (name and rollNumber).
8. Execute the code and we have our expected Table with dynamic rows.

struct ContentView: View {
    private var namesArray = ["Amit", "Javed", "Suhel" , "Suraj"]
    private var rollNosArray = ["01", "02", "03" , "04"]
    var body: some View {
        List (0..<rollNosArray.count) { index in
            DynamicCell(rollNumber: self.rollNosArray[index], name: self.namesArray[index])
        }
    }
}

struct DynamicCell: View {
    var rollNumber = ""
    var name = ""
    var body: some View {
        HStack {
            Text("Roll Number - \(rollNumber)")
            Divider()
            Text("Name - \(name)")
        }
    }
}








Comments

Popular posts from this blog

UITableView - Add or Remove Rows Dynamically (Objective C & Swift Source codes)

payUmoney Payment Gateway Integration in iOS App (Objective C)

Check Internet Connectivity Using AFNetworking 2.0