How to assign an optional Binding parameter in SwiftUI?

前端 未结 4 1114
梦毁少年i
梦毁少年i 2021-01-03 21:38

I\'m trying to build a custom NavBar with some optional Views, like a searchbar (but only if the view needs to display it).

I need to pass

4条回答
  •  遥遥无期
    2021-01-03 22:22

    What you want is an Optional Binding of a String, not a Binding of an Optional String. I don't think you can achieve that by using the @Binding annotation.

    However, you don't need to used the annotation. You can just declare the variable as a Binding:

    Your

    @Binding var searchTxt: String?;
    

    then turns to this

    var searchTxt: Binding
    

    But this way the syntax lets you place the ? wherever you want. So if you move it to the end, after the Binding's closing tag, you have what you want.

    var searchTxt: Binding?
    

    If you want to access the String inside your Binding, you have to use the wrappedValue property.

    Text(searchTxt!.wrappedValue)
    

提交回复
热议问题