SwiftUI Optional TextField

前端 未结 4 2034
佛祖请我去吃肉
佛祖请我去吃肉 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:55

    Ultimately the API doesn't allow this - but there is a very simple and versatile workaround:

    extension Optional where Wrapped == String {
        var _bound: String? {
            get {
                return self
            }
            set {
                self = newValue
            }
        }
        public var bound: String {
            get {
                return _bound ?? ""
            }
            set {
                _bound = newValue.isEmpty ? nil : newValue
            }
        }
    }
    

    This allows you to keep the optional while making it compatible with Bindings:

    TextField($test.bound)
    

提交回复
热议问题