SwiftUI Optional TextField

前端 未结 4 2025
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 08:17

Can SwiftUI Text Fields work with optional Bindings? Currently this code:

struct SOTestView : View {
    @State var test: String? = \"Test\"

    var body: s         


        
4条回答
  •  一生所求
    2020-11-29 08:51

    True, at the moment TextField in SwiftUI can only be bound to String variables, not String?. But you can always define your own Binding like so:

    import SwiftUI
    
    struct SOTest: View {
        @State var text: String?
    
        var textBinding: Binding {
            Binding(
                get: {
                    return self.text ?? ""
            },
                set: { newString in
                    self.text = newString
            })
        }
    
        var body: some View {
            TextField("Enter a string", text: textBinding)
        }
    }
    

    Basically, you bind the TextField text value to this new Binding binding, and the binding redirects it to your String? @State variable.

提交回复
热议问题