SwiftUI - If inside ForEach loop

前端 未结 3 716
猫巷女王i
猫巷女王i 2021-01-18 15:30

I am building a List based on my elements in an array I fetched before.

I am fetching all the entities.. when the user makes a search in the search bar, I want to fi

相关标签:
3条回答
  • 2021-01-18 16:09

    filter your data BEFORE passing it to ForEach constuctor.

    ForEach(self.documentItems.filter {self.checkSearchString(document: $0)}, id: \.self) { document in
        HStack(spacing: 0)
            {
                ListRow(document: document).tag(document)
            }
    }
    
    0 讨论(0)
  • 2021-01-18 16:13

    You need to use Group to wrap different views provided by condition, like below

     ForEach(self.documentItems, id: \.self) { document in
       Group {
         if (self.checkSearchString(document: document))
         {
             HStack(spacing: 0)
             {
                 ListRow(document: document).tag(document)
             }
         }
         else 
         {
            EmptyView()
         }
       }
     }
    
    0 讨论(0)
  • 2021-01-18 16:18
    List(selection: $selectedDocument)
    {
        ForEach(self.documentItems, id: \.self) { document in
    
           self.checkSearchString(document: document) ?  extractedHstack() : emptyView()
    
        }
    

    Extract your hstack and use a trinary with an empty view. Let me know if this works I did this from memory no IDE on this computer.

    0 讨论(0)
提交回复
热议问题