0

I was trying to hide view but noticed that view.hidden() will only hide the view but but the space remains.

I also tried some of the suggestions on this link Dynamically hiding view in SwiftUI But it didn't really work for me, albeit it was a starting point.

Find below what I finally did.

Darotudeen
  • 1,914
  • 4
  • 21
  • 36

2 Answers2

2

Here's an approach without an extension.

struct ContentView: View {
    @State var hidden = false
    @State var text = ""
    var body: some View {
        NavigationView {
            List {
                Section {
                    Toggle("Hide", isOn: $hidden.animation(Animation.easeInOut))
                }
                
                if !hidden {
                    Section {
                        TextField("Pin", text: $text)
                    }
                }
            }
        }
    }
}

hidden

cole
  • 1,039
  • 1
  • 8
  • 35
  • 1
    I am yet to understand why people create overly complex extensions to do things like this instead of keeping it simple like you have done here. – Fogmeister Apr 25 '22 at 19:26
  • @Fogmeister I agree, just keep it simple. Thank you! – cole Apr 25 '22 at 19:28
-2

I created an extension function as below

extension View {
    @ViewBuilder func hiddenConditionally(isHidden: Binding<Bool>) -> some View {
        isHidden.wrappedValue ? self  :  self.hidden() as? Self
    }
}

and you can call it as below

         TextField("Pin", text: $pin)
                .hiddenConditionally(isHidden: $showPinField)
Darotudeen
  • 1,914
  • 4
  • 21
  • 36