Created
February 12, 2024 20:54
-
-
Save ryanlintott/899e5ece172acf768288b5bba2cb56f8 to your computer and use it in GitHub Desktop.
A SwiftUI List where a single item is selected across Sections.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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