skip to Main Content

I am using a button to show/hide a view in SwiftUI. It is working fine when I first tap the button. Like this:

my view

The thing I want is when I first tap it, it has to show me my view. And when I tap it the second time, it has to again hide the view. And on every tap it has to show/hide the view respectively. In storyboard, this scenario is easy to handle but in SwiftUI, I don’t know how to do this as I am new to SwiftUI.

My code is:


import SwiftUI

struct ShowHideText: View {
    
    @State private var showName = false
    
    var body: some View {
        VStack(spacing: 50) {
            
            Text("Users")
                .fontWeight(.bold)
            
            if showName {
                name()
            } else {
                name()
                    .hidden()
            }
            
            
            Button("Show/Hide") {
                showName = true
            }
        }
    }
    
    func name() -> some View {
        
        VStack(spacing: 30) {
            Text("David")
            
            Text("Kate")
        }
        
    }
}

struct ShowHideText_Previews: PreviewProvider {
    static var previews: some View {
        ShowHideText()
    }
}

And one more thing which I need to ask is in my code, if I use .hidden(), the view hides but the space of the view remains there. I don’t know if there is a way that it hides the view and I also have the view’s content as I have to do some work on its content too, or if it works fine if I don’t use .hidden() and name() in else part and I can do some work with its content.

2

Answers


  1. Change

    Button("Show/Hide") {
       showName = true
    }    
    

    to

    Button("Show/Hide") {
       showName.toggle()
    }
    
    Login or Signup to reply.
  2. For second part of your question. Change

    if showName {
        name()
    } else {
        name()
            .hidden()
    }
    

    To

    if showName {
        name()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search