简体   繁体   中英

Update Binding in UIViewRepresentable

I have a swiftUI view that calls a UIViewRepresentable view. In the SwiftUI view I am toggling the state of @State boolean value.

In my UIViewRepresentable view I have created a binding that gets past from the main SwiftUI view. The problem is the binding never gets update or at least the updateView function is not getting called in the UIViewRepresentable view. I fell like I must be doing something wrong but I am just overlooking it. Here is an example of what I am trying to do.

  import Foundation
  import SwiftUI

 struct BindingTest: UIViewRepresentable {

@Binding var status: Bool


func makeUIView(context: Context) -> UIActivityIndicatorView {
    
    let activityIndicator = UIActivityIndicatorView()
    
    activityIndicator.style = .large
    
    return activityIndicator
}

func updateUIView(_ uiView: UIViewType, context: Context) {
    
    
    print("Hello")
    
}

}



 import SwiftUI

 struct ChartView: View {

@State var status = false

var body: some View {

    
    VStack{
        
        Spacer()
    
    Button(action: {
        
       status = !status
        
    }) {
        
        Text("Change")
        
    }

    BindingTest(status: $status)
    
    
        
    }
}
}

I am using Xcode 12.5 and Swift 5.4

Looks like SwiftUI is doing some cleverness under the hood that isn't immediately obvious to us. Because you don't actually use your binding in updateUIView , it's not actually getting called.

However, if you update your code to the following:

func updateUIView(_ uiView: UIViewType, context: Context) {
  print("Hello \(status)")
}

then you'll see that it does, in fact, get called.

PS - you can use status.toggle() instead of status = !status

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM