Hello,
I am attempting to present a list of items in SwiftUI sorted by when they were last used. Current behaviour:
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!
I am attempting to present a list of items in SwiftUI sorted by when they were last used. Current behaviour:
user sees a List of items, sorted with most recently used at the top
user selected item X from the list (navigates to its detail view)
user 'uses' item X in the detail view
user navigates back to list view
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} } }