Home > Enterprise >  Picture and text when clicking on the button. SwiftUI
Picture and text when clicking on the button. SwiftUI

Time:11-04

How to make a picture and text appear when you click on the button?image

VStack {
    Image(systemName: "house.fill").resizable().aspectRatio(contentMode: .fill) .frame(width: 75, height: 75)
    Text("TEST")
    Spacer().frame(height: 100)
    Button(action: { }) {
        Text("TEST").foregroundColor(Color.white).padding()
    }.background(Color.black) .cornerRadius(10)
}

I'm new to swift, Thanks for any help

CodePudding user response:

You can use an if clause to conditionally display elements based on a @State variable.

I'm using the extra frame modifier on the VStack that you didn't originally have to make sure that nothing changes position when the @State variable changes and the elements inside the stack appear/disappear.

struct ContentView : View {
    @State private var showImage = false
    
    var body: some View {
        VStack {
            VStack {
                if showImage {
                    Image(systemName: "house.fill").resizable().aspectRatio(contentMode: .fill).frame(width: 75, height: 75)
                    Text("TEST")
                }
            }.frame(height: 100)
            Spacer().frame(height: 100)
            Button(action: { showImage.toggle() }) {
                Text("TEST").foregroundColor(Color.white).padding()
            }.background(Color.black) .cornerRadius(10) }
    }
}
  • Related