简体   繁体   中英

How do you reorder a SwiftUI list?

I have a list of objects in a SwiftUI list, and I want to be able to filter that list based on user inputs. I have the list resorting, but I don't know how to call "refresh" on the list view

struct VitalsDetailView: View {
    var body: some View {
        var filteredVitals = VitalsManager.sharedInstance.vitals?.vitals?.filter({ $0.name == self.vitalName})
            
        VStack(alignment: .leading, spacing: 5) {
            VStack(alignment: .leading) {
                HStack {
                    Text(NSLocalizedString("VitalsDetails.sortedBy", tableName: nil, bundle: Bundle.main, value: "Sorted By.", comment: ""))
                        .font(.system(size: 13))
                        .fontWeight(.medium)
                    Text(NSLocalizedString("VitalsDetails.dateReported", tableName: nil, bundle: Bundle.main, value: "Date Reported.", comment: ""))
                        .font(.system(size: 13))
                        .fontWeight(.light)
                    Text(displayText)
                        .font(.system(size: 13))
                        .fontWeight(.light)
                    Image(systemName: "arrow.up.arrow.down")
                        .renderingMode(.template)
                        .foregroundColor(.blue)
                }
                .onTapGesture(count: /*@START_MENU_TOKEN@*/1/*@END_MENU_TOKEN@*/, perform: {
                    //reorder list
                    if(newToOld) {
                        filteredVitals = filteredVitals!.sorted(by: {$0.dateOfIssue!.compare($1.dateOfIssue!) == .orderedAscending })
                    } else {
                        filteredVitals = filteredVitals!.sorted(by: {$0.dateOfIssue!.compare($1.dateOfIssue!) == .orderedDescending })
                    }
                })
                Text("Last Updated Date")
                    .font(.system(size: 15))
            }
            .padding()
            
            List(filteredVitals!) { vital in
                vitalsCell(vital: vital)
            }
            
        }
        .frame(minWidth: 0,
               maxWidth: .infinity,
               minHeight: 0,
               maxHeight: .infinity,
               alignment: .topLeading)
        .background(Color((#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1))))
        .navigationBarTitle(vitalName)
    }
}

You can make your filteredVitals as state (or move into view model and make published), ie

struct VitalsDetailView: View {
    @State private var filteredVitals = VitalsManager.sharedInstance.vitals?.vitals?.filter({ $0.name == self.vitalName})

var body: some View {
   // ... other code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM