SwiftUI 隐藏列表单元格(如果为空)
SwiftUI Hide List Cell if its empty
我在使用 SwiftUI 的 Swift5 项目中有一个视图。
这是一个列表视图。
有什么方法可以根据变量的数据从列表中添加或删除 VStack 吗?
我无法在代码的那部分放置任何逻辑,所以现在我很挣扎。
List {
VStack {
Text(txt)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
}
VStack { // this view should be displayed or hidden if the data variable is 0
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .bottomLeading)
}.onReceive(imageLoader.didChange) { data in
self.image = UIImage(data: data) ?? UIImage()
// here I check if there is any kind of data
if data.count == 0 {
print("Data is 0 so there is no image") // in this case I don't need the second VStack
} else {
print("Data is not 0 so there is an image") // in this case I need the second VStack
}
}
}
我从来没有尝试学习 SwiftUI,因为我已经习惯了 Swift5,所以我没有任何 SwiftUI 知识。
这是一个简单的视图,如果您单击按钮,列表中的第一个项目就会消失,如果您再次单击它,它会再次出现:
为了实现这一点,我使用了@State 变量。更改我的视图状态会强制我的视图重新加载。网上有很多不错的文章介绍@State的功能。
import SwiftUI
struct ContentView: View {
@State private var show = true
var body: some View {
VStack {
List {
if show {
Text("Text1")
}
Text("Text2")
Text("Text3")
}
Button(action: {
self.show.toggle()
}) {
Text("Hide Text1")
}
}
}
}
您可以在您的示例中实现相同的目标:
if data.count == 0 {
self.show = false
} else {
self.show = true
}
您可以使用根据数据设置的显示变量来显示视图。
if show {
Text("Text1") // Or whatever view you like
}
我在使用 SwiftUI 的 Swift5 项目中有一个视图。 这是一个列表视图。
有什么方法可以根据变量的数据从列表中添加或删除 VStack 吗?
我无法在代码的那部分放置任何逻辑,所以现在我很挣扎。
List {
VStack {
Text(txt)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
}
VStack { // this view should be displayed or hidden if the data variable is 0
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .bottomLeading)
}.onReceive(imageLoader.didChange) { data in
self.image = UIImage(data: data) ?? UIImage()
// here I check if there is any kind of data
if data.count == 0 {
print("Data is 0 so there is no image") // in this case I don't need the second VStack
} else {
print("Data is not 0 so there is an image") // in this case I need the second VStack
}
}
}
我从来没有尝试学习 SwiftUI,因为我已经习惯了 Swift5,所以我没有任何 SwiftUI 知识。
这是一个简单的视图,如果您单击按钮,列表中的第一个项目就会消失,如果您再次单击它,它会再次出现:
为了实现这一点,我使用了@State 变量。更改我的视图状态会强制我的视图重新加载。网上有很多不错的文章介绍@State的功能。
import SwiftUI
struct ContentView: View {
@State private var show = true
var body: some View {
VStack {
List {
if show {
Text("Text1")
}
Text("Text2")
Text("Text3")
}
Button(action: {
self.show.toggle()
}) {
Text("Hide Text1")
}
}
}
}
您可以在您的示例中实现相同的目标:
if data.count == 0 {
self.show = false
} else {
self.show = true
}
您可以使用根据数据设置的显示变量来显示视图。
if show {
Text("Text1") // Or whatever view you like
}