SwiftUI-如果在ForEach循环中 [英] SwiftUI - If inside ForEach loop
问题描述
我正在基于之前获取的数组中的元素构建列表.
I am building a List based on my elements in an array I fetched before.
我正在获取所有实体.当用户在搜索栏中进行搜索时,我要过滤我的列表.我不是在做一个新的FetchRequest,我只是想过滤我的对象.
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)
}
}
我有一个列表,然后是我的ForEach循环.在该循环中,我想确定是否显示该元素.问题是,即使我不想显示该元素,列表中仍然有一个小视图.我知道为什么,这是因为我仍然渲染该HStack()
.
我基本上需要将HStack()
拖动到我的If
内,但这对我不起作用.我认为这是因为我需要在列表中渲染一个视图.但是,如何在不渲染某些内容的情况下延续我的ForEach
.
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)
}
}
提前谢谢!
推荐答案
在将数据传递给ForEach构造函数之前对其进行过滤.
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)
}
}
这篇关于SwiftUI-如果在ForEach循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!