【问题标题】:SwiftUI Hide List Cell if its emptySwiftUI 隐藏列表单元格(如果为空)
【发布时间】:2020-03-09 21:10:35
【问题描述】:

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

【问题讨论】:

    标签: swift swiftui swiftui-list


    【解决方案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
    }
    

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

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

    【讨论】:

    • 非常感谢。出于某种原因,data.count == 0 中的打印不会打印任何内容,但视图工作正常,所以我不在乎。再次感谢先生:D
    猜你喜欢
    • 2015-12-08
    • 2022-01-16
    • 2012-02-18
    • 2012-01-10
    • 2014-09-06
    • 2012-05-20
    • 1970-01-01
    • 2012-08-14
    • 2017-12-11
    相关资源
    最近更新 更多