Skip to content

Instantly share code, notes, and snippets.

@rebornix
Created December 22, 2019 06:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebornix/5b6f0599161f9081eab84920c5f84691 to your computer and use it in GitHub Desktop.
Save rebornix/5b6f0599161f9081eab84920c5f84691 to your computer and use it in GitHub Desktop.
SwiftUI list view selection & navigation
import SwiftUI
struct Task: Codable, Identifiable, Hashable {
var id: Int
var name: String
}
struct ContentView: View {
@State private var tasks: [Task] = [
Task(id: 0, name: "Fix #1"),
Task(id: 1, name: "Fix #2"),
Task(id: 2, name: "Fix #3"),
Task(id: 3, name: "Fix #4"),
Task(id: 4, name: "Fix #5")
]
@State private var selection: Task?
@State var action: Int?
var body: some View {
NavigationView {
List(selection: $selection) {
ForEach(tasks, id: \.self) { task in
NavigationLink(destination: VStack {
Text(task.name)
Button("Random Select") {
self.selection = self.tasks.randomElement()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity), tag: task.id, selection: self.$action) {
VStack {
Text(task.name)
}
}
}
}
VStack {
Text("Please select one task")
Button("Random Select") {
self.selection = self.tasks.randomElement()
self.action = self.selection?.id
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment