Skip to content
Sortable Table preview
Rendered from the SwiftUI source on this page.

Sortable Table

From syxUI — written for both platforms, not translated between them.

A sortable table with an active sort column and direction caret.

Cards · SwiftUI · iOS 17

  • cards
  • swiftui

The actual source

TableSortable.swift
// Sortable Table · syxUI · https://syxui.dev/components/table-sortable
// Free in any project. Keep this line and credit syxUI where a person can read it.

import SwiftUI

let tblBlue = Color(red: 0.0, green: 0.47, blue: 1.0)

extension View {
    func tblCard(_ w: CGFloat) -> some View {
        self.frame(width: w)
            .background(Color(.systemBackground), in: RoundedRectangle(cornerRadius: 18, style: .continuous))
            .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
            .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).stroke(Color.primary.opacity(0.08), lineWidth: 1))
            .shadow(color: .black.opacity(0.04), radius: 10, x: 0, y: 4)
    }
}

/// Sortable table - active sort column tinted with a direction caret in the header.
struct TableSortable: View {
    let rows: [(String, String, String)] = [
        ("Emma Stone", "$4,820", "98"), ("Liam Carter", "$3,910", "92"),
        ("Ava Nguyen", "$3,540", "88"), ("Noah Kim", "$2,760", "81"),
    ]
    var body: some View {
        VStack(spacing: 0) {
            HStack {
                Text("Name").frame(maxWidth: .infinity, alignment: .leading)
                HStack(spacing: 3) {
                    Text("Revenue")
                    Image(systemName: "arrow.down").font(.system(size: 9, weight: .bold))
                }.foregroundStyle(tblBlue).frame(width: 84, alignment: .trailing)
                Text("Score").frame(width: 48, alignment: .trailing)
            }
            .font(.system(size: 12, weight: .semibold)).foregroundStyle(.secondary)
            .padding(.horizontal, 16).padding(.vertical, 11)
            .background(Color.primary.opacity(0.03))
            Divider()
            ForEach(Array(rows.enumerated()), id: \.offset) { i, r in
                HStack {
                    Text(r.0).font(.system(size: 14, weight: .medium)).frame(maxWidth: .infinity, alignment: .leading)
                    Text(r.1).font(.system(size: 14, weight: .semibold).monospacedDigit()).frame(width: 84, alignment: .trailing)
                    Text(r.2).font(.system(size: 14).monospacedDigit()).foregroundStyle(.secondary).frame(width: 48, alignment: .trailing)
                }
                .padding(.horizontal, 16).padding(.vertical, 12)
                if i < rows.count - 1 { Divider().padding(.leading, 16) }
            }
        }
        .tblCard(330)
    }
}
iOS 17 · No dependencies

Dependencies

SwiftUI
No external dependencies

Requires iOS 17