Lead 1 scaled

Jul 29, 2021 swiftui

How to create a TableView in SwiftUI using List and VStack

Hi Guys Today we going to start with Add the TableView using SwiftUI. At WWDC 2020 Apple introduce SwiftUI LazyVStack . we can develop the Tableview using List as well as VStack.

Lets start with the TableView in SwiftUI using List

1) Open the Xcode Chose the Templete as Single App as  shown in Below Image

image

2)Click Next  Add the Product Name and change the interference as SwiftUI Chose the Language Swift

image 1

3) Click on the ContentView as Shown in Image

image 2

Use List as  TableView in Swift UI .Add the Following Code in the Content View

struct ContentView: View {

    var body: some View {

        List(1..<5) {_ in

            Text("Placeholder")

        }

    }

}

Run the code and Check the Preview

image 3

SwiftUI has Introduce the LazyVStack  on WWDC 2020 .It is suitable with iOS 14 and Above.

Follow the Previous 3 Step instead of List we can use LazyVStack in the ContentView   .Add the follwoing code in the content view

struct ContentView: View {

    var body: some View {

        LazyVStack(alignment: .leading, spacing: 10content: {

            ForEach(1...15, id: .self) { count in

                Text("Placeholder (count)")

            }

        })

    }

}
image 4

To Work like TableView add ScrollView before LazyVStack so that it can be easily worked as TableView

struct ContentView: View {

    var body: some View {

        ScrollView {

        LazyVStack(alignment: .leading) {

            ForEach(1...15, id: .self) { count in

                Text("Placeholder (count)")

            }.padding()

        }

        }

    }

}

We  can add sectionHeader for LazyVStack

struct SectionHeaderView: View {

    var body: some View {

        VStack {

            Text("LeadByCode")

                .foregroundColor(.white)

                .font(.title)

        }

        .frame(width: UIScreen.main.bounds.width, height: 50)       .background(Color.gray)

    }

}

Add the SectionHeaderView inside the LazyVstack

struct ContentView: View {

    var body: some View {

        ScrollView {

            LazyVStack(alignment: .leading, pinnedViews: [.sectionHeaders]){

            Section(header: SectionHeaderView()){

            ForEach(1...15, id: .self) { count in

                Text("Placeholder (count)")

            }.padding()

        }

            }

        }.edgesIgnoringSafeArea(.top)

    }

}

thus we have implemented TableView using both LazyVStack and also the List

For More Topics : –

How to Pass Data between View in SwiftUI

What is View Controller? What is its lifecycle?

What is Core Data with Swift Interview Question