Home > Blockchain >  Swift table only show 1 column
Swift table only show 1 column

Time:01-30

I am new to Xcode, and facing some issues while creating a table view.

Problem: In iOS 14 Plus simulator, only 1 columns is shown - "Category" and without header. The entire column "Total" is completely missing. However, when I switch the simulation to ipad, everything is working fine. Really appreciate if someone could help to resolve this issue.

struct OverallObj: Identifiable {
    var category: String
    var total: Int
    var id: String {
        category
    }

    static var summary: [OverallObj] {
        [
            OverallObj(category: "1st", total: 1000),
            OverallObj(category: "2nd", total: 1000)
        ]
    }
}

var body: some View {
    Table(overallView) {
        TableColumn("Category", value: \.category)
        TableColumn("Total") { overallObj in
            Text("\(overallObj.total)")
        }
    }
}

I am expecting the table to show 2 columns - "Category" and "Total" with headers

CodePudding user response:

The problem in your specific case is caused by the compact horizontal size on iOS.
From the official documentation:

MacOS and iPadOS support SwiftUI tables. On iOS, and in other situations with a compact horizontal size class, tables don’t show headers and collapse all columns after the first. If you present a table on iOS, you can customize the table’s appearance by implementing compact-specific logic in the first column.

You can implement compact-specific logic in the first column of a table in SwiftUI by using the environment modifier and checking the sizeCategory environment value.
If the size category is compact, you can return a compact version of the view for the first column with all the data you need to display, otherwise return the normal version of the view.

Here is an example:

var body: some View {
    Table(overallView) {
        TableColumn("Category") { item in
            if self.environment.sizeCategory == .compact {
                // Return compact version of the view
                Text("Compact")
            } else {
                // Return normal version of the view
                Text("Normal")
            }
        }
        TableColumn("Total") { overallObj in
        Text("\(overallObj.total)")
    }
}

CodePudding user response:

Using tables on different platforms macOS and iPadOS support SwiftUI tables. On iOS, and in other situations with a compact horizontal size class, tables don’t show headers and collapse all columns after the first. If you present a table on iOS, you can customize the table’s appearance by implementing compact-specific logic in the first column.

Source: https://developer.apple.com/documentation/SwiftUI/Table

  • Related