SwiftUI Table Tutorial

SwiftUI’s Table view offers a flexible way to create multi-column lists, presenting data efficiently in a structured, tabular format.
Written by

Joash Tubaga

Updated on

Aug 06 2024

Table of contents

    Overview

    SwiftUI’s Table view provides a powerful and flexible way to create multi-column lists, enabling developers to present data in a structured, tabular format. This article explores how to implement and use the Table view in SwiftUI to display data in multiple columns efficiently.

    Code Snippet

    Swift
    import SwiftUI
    
    struct Employee: Identifiable {
        let id = UUID() // Unique identifier for each employee
        let name: String
        let occupation: String
    }
    
    struct ContentView: View {
        let data = [
            Employee(name: "John Doe", occupation: "Software Developer"),
            Employee(name: "Jane Smith", occupation: "Project Manager"),
            Employee(name: "Sam Johnson", occupation: "Designer")
        ]
    
        var body: some View {
            Table(data) {
                TableColumn("Name", value: \.name)
                TableColumn("Occupation", value: \.occupation)
            } 
        }
    }

    Code Explanation

    • struct Employee: Defines a structure for employee data that includes unique identifiers (id), names, and occupations. This struct conforms to the Identifiable protocol, which is necessary for using each instance in a SwiftUI Table.
    • Table(data) { ... }: Constructs a table using the array of Employee objects. Each Employee is represented in the table with rows that bind to the name and occupation properties.
    • TableColumn("Name", value: \.name): Specifies a table column for employee names.
    • TableColumn("Occupation", value: \.occupation): Specifies another column for displaying the occupation of each employee.

    Using Table in SwiftUI provides a straightforward way to create multi-column lists, making it easier to present complex data in a readable and organized format. This feature is particularly useful for iPadOS and macOS applications that require displaying tabular data, such as contact lists, data reports, or any scenario where structured information is essential. By leveraging SwiftUI’s declarative syntax, developers can quickly implement and customize tables to suit their app’s needs.



    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris