How to assign an optional Binding parameter in SwiftUI?

前端 未结 4 1091
梦毁少年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<String?>
    

    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<String>?
    

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

    Text(searchTxt!.wrappedValue)
    
    0 讨论(0)
  • 2021-01-03 22:23
    @Binding var searchTxt: String?
    
    init(searchTxt: Binding<String?>?) {
        self._searchTxt = searchTxt ?? Binding.constant(nil)
    }
    
    0 讨论(0)
  • 2021-01-03 22:24

    So below is example to use optional Binding and how to access the binding and toggle to show some view:

    struct NavBar: View {
        @Binding var showUser: Bool
        var showOptional: Binding<Bool>?
        
        var body: some View {
        
        VStack {
         Button(action: { showUser.toggle() },
                label: { Text("NOT OPTIONAL") })
        
         Button(action: { showSelectBuddy?.wrappedValue.toggle()) },
                label: { Text("NOT OPTIONAL") })
        
        }
        }
        }
    
        struct UseNavbar: View {
        
        @State var showoptional = false
        @State var show = false 
        
        var body: some View {
        Text("Optional")
        .navigationBarItems(leading:
        NavBar(showUser: show), trailing: NavBar(showUser: show, showOptional: showoptional))
        }
        }
    
    0 讨论(0)
  • 2021-01-03 22:27

    I have a UIViewControllerRepresentable in order to use UIImagePickerController. If you've ever used this image picker, you know that you need to image returned to be an optional. So in my ContentView I declared:

    @State var uiImage: UIImage?
    
    ...
    
    if uiImage != nil {
        Image(uiImage: $uiImage
    } else {
        Rectangle()
    }
    

    And in my ImagePicker (that's my SwiftUI view) I have:

    @Binding var uiImage: UIImage?
    

    Works like a charm.

    (The if statement is pretty much psuedo-code, as I'm actually using an MTKView and a CIImage, but your get the drift - you use the optional just as you would anywhere else.)

    0 讨论(0)
提交回复
热议问题