Tuesday, July 2, 2019

How to create TableView (List) in SwiftUI?


Project Link : https://github.com/EdyLucky/TableView-List-SwiftUI

List keyword has been used to create TableView in SwiftUI. We just need to add below code to create simple static tableview.

import SwiftUI

struct ContentView : View {
    var body: some View {
       
        List {
            Text("First Row")
            Text("Second Row")
            Text("Second Row")
        }
       
    }
}

To make dynamic List (TableView), we will create custom Array and import images to our project which have same name as array items. (Images can be downloaded from the link to github account above)



First we will create titles array and use array inside list as shown below.


import SwiftUI

struct ContentView : View {
    var titles = ["Swift", "SwiftUI", "Xcode", "iOS", "Mac"]

    var body: some View {
        List(0..<titles.count) { index in
            Text(self.titles[index])
        }
    }
}

To add images to our List we need to create Image view and add both image and text views in Horizontal Stack as shown below.  By adding frame and .clipShape(Circle())
properties we can adjust image size and make it circular.

import SwiftUI

struct ContentView : View {
    var titles = ["Swift", "SwiftUI", "Xcode", "iOS", "Mac"]

    var body: some View {
        List(0..<titles.count) { index in
          Image(self.titles[index]).resizable()
                .frame(width: 60, height: 60)
            Text(self.titles[index])
        }
    }
}

To add header to the List we need to embed this list inside NavigationView and set NavigationBarTitle

import SwiftUI

struct ContentView : View {
    var titles = ["Swift", "SwiftUI", "Xcode", "iOS", "Mac"]

    var body: some View {
        NavigationView {
            List(0..<titles.count) { index in
                HStack {
                    Image(self.titles[index]).resizable()
                        .frame(width: 60, height: 60)
                    Text(self.titles[index])
                }
            }
            .navigationBarTitle(Text("Apple List"), displayMode: .large)
        }
    }
}








No comments:

Post a Comment