Having trouble changing updating swiftUI List display when sort order changes...

Hello,

I am attempting to present a list of items in SwiftUI sorted by when they were last used. Current behaviour:
  1. user sees a List of items, sorted with most recently used at the top

  2. user selected item X from the list (navigates to its detail view)

  3. user 'uses' item X in the detail view

  4. user navigates back to list view

expected behaviour: item X at the top of the list
actual behaviour: item X is still in its previous location
(see code below)

When I uncomment line 27, tapping the user button immediately (and unexpectedly) takes the user back to the list view. Is there a way I can leave the user on the detail view, but have the list be sorted when I go back to the list view?
thanks!

Code Block
import SwiftUI
struct ContentView: View {
    @ObservedObject var list = ModelList.shared
    var body: some View {
        NavigationView {
            List(list.sorted()) {object in
                NavigationLink(destination: DetailView(object: object)) {
                    Text(object.title)
                }
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
struct DetailView: View {
    var object: ModelObject
    var body: some View {
        VStack {
            Text(object.title)
            Button("Use") {
                self.object.usedDate = Date()
/*                ModelList.shared.objectWillChange.send() */
            }
        }
    }
}
class ModelObject: ObservableObject {
    @Published var usedDate: Date = Date(timeIntervalSince1970: 0)
    let title: String
    init(title: String) {
        self.title = title
    }
}
extension ModelObject: Identifiable {
}
class ModelList: ObservableObject {
    static let shared = ModelList()
    @Published var objects: [ModelObject]
    init() {
        self.objects = [ModelObject(title: "first"), ModelObject(title: "second")]
    }
    func sorted() -> [ModelObject] {
        return objects.sorted{$0.usedDate > $1.usedDate}
    }
}




Answered by BabyJ in 629606022
You can use an .onAppear modifier on the List so that when the list appears the code you specified is run.
Accepted Answer
You can use an .onAppear modifier on the List so that when the list appears the code you specified is run.
thanks BabyJ. That did the trick!
Having trouble changing updating swiftUI List display when sort order changes...
 
 
Q