SwiftUI隐藏列表单元格(如果为空)

时间:2020-03-09 21:10:35

标签: swift swiftui swiftui-list

我在使用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知识。

1 个答案:

答案 0 :(得分:1)

这里有一个简单的视图,如果单击按钮,列表中的第一项将消失,如果再次单击它,它将再次显示:

要达到这个目的,我使用一个@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
}

您可以使用基于数据设置的show变量来显示视图。

if show {
    Text("Text1") // Or whatever view you like
}