SwiftUI List 和 For Each 循环与空白元素

Posted

技术标签:

【中文标题】SwiftUI List 和 For Each 循环与空白元素【英文标题】:SwiftUI List's and For Each loop with blank elements 【发布时间】:2021-07-16 19:09:31 【问题描述】:

我正在使用一个列表和一个 ForEach 视图来循环遍历核心数据,但我只想显示符合我的 if 语句的对象,但如果它不显示,它仍然会为对象创建一个空白列表槽,创建不适合的对象的大空间。

    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)
                        
                    
                
            
        

任何帮助将不胜感激。

【问题讨论】:

为什么不直接将过滤器添加到用于获取数据的 NSFetch 请求的谓词中? 【参考方案1】:

目前,无论nextMonthList 是真还是假,您总是有一个HStack。只需删除第一个HStack 并将if 直接放在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)
        
    

【讨论】:

以上是关于SwiftUI List 和 For Each 循环与空白元素的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI ForEach Binding 编译时错误看起来不像 for-each

SwiftUI 在 For Each 中获取下一个循环的值

自旋锁 list_for_each_entry_safe 或 list_for_each_entry 是不是安全?

list_for_each_entry解析

for+next()实现数组的遍历及while list each 的使用

jQuery$.each循环遍历详解,各种取值对比,$.each遍历数组对象Dom元素二维数组双层循坏类json数据等等