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()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With