UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to pass an optional Binding to a View?

Forums > SwiftUI

I have a view which I use in several places in the app. Some of the time, I want it to prompt for three inputs; some of the time, only for two (obviously, I'm simplifying). I want to be able to call

MyView(a: $one, b: $two, c: $three)

or

MyView(a: $one, c: $three)

MyView has an if {} block which controls whether it shows a request for b.

I'm tying myself in knots trying to work out how to declare MyView. Should b be @Binding var String?, or var Binding<String>?, or Binding <String?>, and how do I write the init functions?

Any help gratefully received.

Jeremy

2      

You can do it like this:

struct OptionalBindingView: View {
    var a: Binding<String>
    var b: Binding<String>? = nil
    var c: Binding<String>

    var body: some View {
        VStack(spacing: 20) {
            TextField("A", text: a)
            if let b = b {
                TextField("B", text: b)
            }
            TextField("C", text: c)
        }
        .textFieldStyle(RoundedBorderTextFieldStyle())
        .padding(.horizontal)
    }
}

struct ContainerView: View {
    @State private var a = ""
    @State private var b = ""
    @State private var c = ""

    var body: some View {
        VStack {
            OptionalBindingView(a: $a, b: $b, c: $c)

            Spacer()

            OptionalBindingView(a: $a, c: $c)
        }
    }
}

2      

On many occasions when Holmes explained how he had reached a conclusion, Watson would say "How absurdly simple", which would sometimes cause irritation.

How absurdly simple! (no irritation intended).

Thanks

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.