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.
You can apply a foregroundStyle
to the Table
. Here is a simple example of a table displaying some Person
s:
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...
}
2