SwiftUI List's and For Each loop with blank elements

Viewed 195

I am using a list and a ForEach view to loop through Core Data but I only want to objects that conform with my if statement to show up but if it doesn't it still creates a blank list slot for the object, creating large spaces for the objects that don't fit.

    List {
            Text("LOF's")
                .bold()
            ForEach(customered) {that in
                HStack{
                    if(nextMonthList(serviceMonth: that.nextService ?? Date())){
                        HStack{
                            Text(that.name ?? "Unknown")
                                .padding(.horizontal)
                            Text(that.address ?? "Unknown")
                                .padding(.horizontal)
                            Spacer()
                            Button("Serviced"){
                                that.nextService = Calendar.current.date(byAdding:   .year, value: 1, to: that.nextService ?? Date()) ?? Date()
                                try? self.moc.save()
                            }
                            .padding(.horizontal)
                        }
                    }
                }
            }
        }

Any Help would be greatly appreciated.

1 Answers

Currently, you always have an HStack, no matter whether nextMonthList is true or false. Just remove that first HStack and put the if directly inside the ForEach.

ForEach(customered) {that in
    
    /// directly in the ForEach
    if nextMonthList(serviceMonth: that.nextService ?? Date()) {
        HStack {
            Text(that.name ?? "Unknown")
                .padding(.horizontal)
            Text(that.address ?? "Unknown")
                .padding(.horizontal)
            Spacer()
            Button("Serviced") {
                that.nextService = Calendar.current.date(byAdding:   .year, value: 1, to: that.nextService ?? Date()) ?? Date()
                try? self.moc.save()
            }
            .padding(.horizontal)
        }
    }
}
Related