I have a SwiftUI app with a List displaying an array of model objects. When the user taps a list item we see its detail view.
I want to add previous and next buttons to my detail view, but I'm not sure what needs to happen when previous/next are tapped. (see code below for what I'm looking to do)
My first thought is to make the model variable in the DetailView be a binding, but I'm not sure how this would tie in with the NavigationLink 'stuff'
any/all suggestions appreciated.
thanks!
I want to add previous and next buttons to my detail view, but I'm not sure what needs to happen when previous/next are tapped. (see code below for what I'm looking to do)
My first thought is to make the model variable in the DetailView be a binding, but I'm not sure how this would tie in with the NavigationLink 'stuff'
any/all suggestions appreciated.
thanks!
Code Block class Model: Identifiable { var modelValue: Int init(modelValue: Int) { self.modelValue = modelValue } static let testData = [Model(modelValue: 3), Model(modelValue: 7), Model(modelValue: 31)] } class ModelManager { static let shared = ModelManager() let modelList = Model.testData func previous(for model: Model) -> Model? { if let index = modelList.firstIndex(where: {$0.modelValue == model.modelValue}) { if index > 0 { return modelList[index - 1] } } return nil } func next(for model: Model) -> Model? { if let index = modelList.firstIndex(where: {$0.modelValue == model.modelValue}) { if index < modelList.count - 1 { return modelList[index + 1] } } return nil } } struct ContentView: View { let manager:ModelManager = ModelManager.shared var body: some View { NavigationView { List(manager.modelList) { object in NavigationLink( destination: DetailView(model: object, previous: manager.previous(for: object), next: manager.next(for: object)), label: { Text("fred \(object.modelValue)") }) } } } } struct DetailView: View { var model: Model var previous: Model? var next: Model? var body: some View { VStack { HStack { if previous != nil { Button("Previous") { // goto previous } } Spacer() if next != nil { Button("Next") { // goto next } } } Text("value: \(model.modelValue)") Spacer() } } }