Skip to content

Instantly share code, notes, and snippets.

@ryanlintott
Created February 12, 2024 20:54
Show Gist options
  • Save ryanlintott/899e5ece172acf768288b5bba2cb56f8 to your computer and use it in GitHub Desktop.
Save ryanlintott/899e5ece172acf768288b5bba2cb56f8 to your computer and use it in GitHub Desktop.
A SwiftUI List where a single item is selected across Sections.
import SwiftUI
struct Theme: Identifiable {
let id: UUID
let name: String
}
extension Theme {
static let blue = Self(id: UUID(), name: "Blue")
static let red = Self(id: UUID(), name: "Red")
}
enum ThemeCategory: String, Identifiable, Hashable, CaseIterable {
case new
case sister
var id: Self { self }
}
struct ThemeListID: Hashable {
let themeID: Theme.ID
let categoryID: ThemeCategory.ID
}
struct ThemeList: View {
@State private var selection: ThemeListID? = nil
var body: some View {
VStack {
List(selection: $selection) {
ForEach(ThemeCategory.allCases) { category in
Section(category.rawValue) {
ForEach([Theme.blue, .red]) { theme in
Text(theme.name)
.tag(ThemeListID(themeID: theme.id, categoryID: category.id))
}
}
}
}
Text("Selection: \(String(describing: selection))")
}
}
}
#Preview {
NavigationStack {
ThemeList()
.toolbar {
EditButton()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment