1
votes

I have a view in my Swift5 project where I use SwiftUI. It's a List View.

Is there any way to add or remove a VStack from the list depending on a variable's data?

I can't place any logic in that part of the code so now I'm struggling.

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
                }
            }
        }

I've never tried to learn SwiftUI, because I got used to Swift5 so I don't have any kind of SwiftUI knowledge.

1

1 Answers

1
votes

Heres a simple view, if you click on the button the first item inside the List disappears and if you click it again it shows up again:

To achive this I use a @State Variable. Changing the State of my view forces my view to reload. There are many nice articles online that describe the functionality of @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")
            }
        }
    }
}

You can achive the same in your example:

if data.count == 0 {
   self.show = false
} else {
   self.show = true
}

you can use the show variable that you set based on the data to display a view.

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