简体   繁体   中英

SwiftUI - If inside ForEach loop

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 filter my List. I am NOT doing a new FetchRequest, I just want to filter my objects.

That is the code I am using at the moment:

List(selection: $selectedDocument)
{
    ForEach(self.documentItems, id: \.self) { document in
        HStack(spacing: 0)
        {
            if (self.checkSearchString(document: document))
            {
                ListRow(document: document).tag(document)
            }
    }

I am having a List, then my ForEach loop. In that loop, I want to decide if I show that element or not. The problem is, that even if I do not want to show the element, there is still a small view inside my List. I know why , it is because I still render that HStack() . I basically need to drag that HStack() inside my If , however that is not working for me. I think it is because I need to render a view inside my List. But how can I contiuue my ForEach without rendering something.

That is what I want to achieve, BUT it is not working:

 List(selection: $selectedDocument)
 {
     ForEach(self.documentItems, id: \.self) { document in
         if (self.checkSearchString(document: document))
         {
             HStack(spacing: 0)
             {
                 ListRow(document: document).tag(document)
             }
         }

Thanks in advance!

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)
        }
}

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()
     }
   }
 }
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.

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