How to assign an optional Binding parameter in SwiftUI?

前端 未结 4 1110
梦毁少年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: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.)

提交回复
热议问题