1
Table(studentRecords, selection: $selectedStudentID) {
                TableColumn("First Name", value: \.firstName)
                TableColumn("Last Name", value: \.lastName)
}

How would I go about setting foregroundStyle to primary, - swiftUI tables seem to set this for the first column and then following columns are as .secondary.

foregroundStyle is not accessible when I have the columns set up in this way.

1 Answer 1

1

You can apply a foregroundStyle to the Table. Here is a simple example of a table displaying some Persons:

struct Person: Identifiable {
    let firstName: String
    let lastName: String
    var id: String { "\(firstName) \(lastName)" }
}

let people = [
    Person(firstName: "John", lastName: "Doe"),
    Person(firstName: "Mary", lastName: "Sue"),
    Person(firstName: "Albert", lastName: "Einstein")
]

struct ContentView: View {
    var body: some View {
        NavigationStack {
            Table(people) {
                TableColumn(Text("First Name").foregroundStyle(Color.accentColor), value: \.firstName)
                TableColumn(Text("Last Name").foregroundStyle(Color.accentColor), value: \.lastName)
            }
            .foregroundStyle(.foreground)
        }
    }
}

Because I only passed one argument to foregroundStyle, there is only one level of hierarchy, and all the columns will use the same style.

I also applied .foregroundStyle(Color.accentColor) to the column headers, because that is the default behaviour of tables on iPadOS (assuming you are targeting iPadOS). Before iOS 17, you should use foregroundColor instead.

If you want to apply further styling to individual columns, you can always pass a custom View to TableColumn.init, e.g.

TableColumn(Text("First Name").foregroundStyle(Color.accentColor)) { person in
    Text(person.firstName)
        // ... style this Text using view modifiers as usual...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! When I try to apply .accent to the column headers I get a type check... I guess I will have to split it up.
@alexc0082 What is your actual code? You should be able to directly copy and paste the code in the answer into a new project and see it working. Please show a minimal reproducible example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.