Created
May 22, 2024 06:38
-
-
Save donnywals/f09317ab281b659c0ccfa4ea06d5d908 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ContentView: View { | |
@State private var exercises: [Exercise] = Exercise.sample | |
var body: some View { | |
NavigationSplitView(sidebar: { | |
ExercisesList(exercises: exercises) | |
}, detail: { | |
ExerciseDetail(exercise: exercises.first!) | |
}) | |
} | |
} | |
struct ExercisesList: View { | |
let exercises: [Exercise] | |
@State var activeItem: Exercise? | |
var body: some View { | |
List(exercises, id: \.id, selection: $activeItem) { exercise in | |
NavigationLink(value: exercise, label: { | |
ExerciseListItem(exercise: exercise) | |
}) | |
} | |
.onAppear(perform: { | |
if activeItem == nil { | |
activeItem = exercises.first | |
} | |
}) | |
.navigationTitle("My exercises") | |
// Need to use this one so we can get the iPad split view to work with list selection | |
.navigationDestination(item: Binding<Exercise?>(get: { | |
activeItem | |
}, set: { newValue in | |
// Use a custom binding to prevent unwanted deselection on iPad | |
guard let newValue else { | |
return | |
} | |
activeItem = newValue | |
}), destination: { exercise in | |
ExerciseDetail(exercise: exercise) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I made some guesses about the nature of your project, but does this work the way you expect it to? It sets a default item, and it updates the detail with the current selection.