将数据从ViewController传递到SwiftUI中的Representable

11
我正在进行物体检测,并使用UIViewControllerRepresentable将我的视图控制器添加到项目中。问题是我无法从ViewController传递数据到我的SwiftUI视图,虽然我可以打印出来。
请问是否有人能帮助我?这是我的代码:
//

import SwiftUI
import AVKit
import UIKit
import Vision
let SVWidth = UIScreen.main.bounds.width

struct MaskDetectionView: View {
    let hasMaskColor = Color.green
    let noMaskColor = Color.red
    let shadowColor = Color.gray
    
    var body: some View {
        VStack(alignment: .center) {
            VStack(alignment: .center) {
                Text("Please place your head inside the bounded box.")
                    .font(.system(size: 15, weight: .regular, design: .default))
                Text("For better result, show your entire face.")
                    .font(.system(size: 15, weight: .regular, design: .default))
            }.padding(.top, 10)
            
            VStack(alignment: .center) {
                SwiftUIViewController()
                    .frame(width: SVWidth - 30, height: SVWidth + 30, alignment: .center)
                    .background(Color.white)
                    .cornerRadius(25)
                    .shadow(color: hasMaskColor, radius: 7, x: 0, y: 0)
                    .padding(.top, 30)
                Spacer()

///      VALUE HERE
            }

        }.padding()
    }
}

struct MaskDetectionView_Previews: PreviewProvider {
    static var previews: some View {
        MaskDetectionView()
        
    }
}


class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {

    
    var result = String()
    //ALL THE OBJECTS
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1 - start session
        let capture_session = AVCaptureSession()
        //capture_session.sessionPreset = .vga640x480
        
        // 2 - set the device front & add input
        guard let capture_device = AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: .video, position: .front) else {return}
        
        guard let input = try? AVCaptureDeviceInput(device: capture_device) else { return }
        capture_session.addInput(input)
        
        // 3 - the layer on screen that shows the picture
        let previewLayer = AVCaptureVideoPreviewLayer(session: capture_session)
        view.layer.addSublayer(previewLayer)
        previewLayer.frame.size = CGSize(width: SVWidth, height: SVWidth + 40)
        previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        
        // 4 - run the session
        capture_session.startRunning()
        
        // 5 - the produced output aka image or video
        let dataOutput = AVCaptureVideoDataOutput()
        dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
        capture_session.addOutput(dataOutput)
    }
    
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection){
        // our model
        
        guard let model = try? VNCoreMLModel(for: SqueezeNet(configuration: MLModelConfiguration()).model) else { return }
        // request for our model
        let request = VNCoreMLRequest(model: model) { (finishedReq, err) in
            if let error = err {
                print("failed to detect faces:", error)
                return
                
            }
            //result
            guard let results = finishedReq.results as? [VNClassificationObservation] else {return}
            guard let first_observation = results.first else {return}
            
            self.result = first_observation.identifier
            print(self.result)
            
        }
        
        guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {return}
        try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
    }

}






struct SwiftUIViewController: UIViewControllerRepresentable {
    
    func makeUIViewController(context: Context) -> ViewController{
        return ViewController()
    }
    
    func updateUIViewController(_ uiViewController: ViewController, context: Context) {
        
    }
    
}





我在 makeUIViewControllerupdateUIViewController 中没有看到传递数据的代码。你为什么没有添加呢? - Cristik
嗨。我不知道该怎么做。我是一名数据科学家,也是iOS的初学者。我只需要在我的应用程序中使用相机,并在其下方获取我的CoreML模型预测的结果。 - Yonus
你能帮我吗?我该怎么实现它?我已经看了 Stack Overflow 上的几乎所有帖子,但是什么都找不到... :(( - Yonus
你想传递什么类型的数据给视图控制器?这些数据来自哪里? - Cristik
基本上,我有SqueezNet模型。在视图控制器中,我有我的自定义相机,对吧?然后,我的SqueezNet将预测ViewController中的项目,如您所见,然后我希望在我的视图中显示预测“字符串”。我可以打印该值,但无法将其传递到我的SwiftUI视图之外。我认为问题是因为它在函数内部?我不知道。 - Yonus
绑定是双向的方式... 你只需要在你的视图控制器内部传递它。这里有一个解决方案的例子https://stackoverflow.com/a/63942901/12299030。 - Asperi
3个回答

36
惯用的方式是在 UI 层次结构中传递一个 Binding 实例——包括 SwiftUI 和 UIKit 代码。无论谁进行更改,Binding 都会自动更新连接到它的所有视图上的数据。数据流程的示意图可能类似于这样:enter image description here。 好了,让我们来谈具体实现细节,首先你需要一个 @State 来存储从 UIKit 端传来的数据,以便将其更新并提供给视图控制器:
struct MaskDetectionView: View {
    @State var clasificationIdentifier: String = ""

接下来,您需要将此传递给视图控制器和SwiftUI视图:

var body: some View {
    ...
    SwiftUIViewController(identifier: $clasificationIdentifier)
    ...
    // this is the "VALUE HERE" from your question
    Text("Clasification identifier: \(clasificationIdentifier)")

现在,您已经正确地注入了绑定,需要更新UIKit端的代码以允许接收绑定。

将您的视图可表示性更新为类似以下内容:

struct SwiftUIViewController: UIViewControllerRepresentable {
    
    // this is the binding that is received from the SwiftUI side
    let identifier: Binding<String>
    
    // this will be the delegate of the view controller, it's role is to allow
    // the data transfer from UIKit to SwiftUI
    class Coordinator: ViewControllerDelegate {
        let identifierBinding: Binding<String>
        
        init(identifierBinding: Binding<String>) {
            self.identifierBinding = identifierBinding
        }
        
        func clasificationOccured(_ viewController: ViewController, identifier: String) {
            // whenever the view controller notifies it's delegate about receiving a new idenfifier
            // the line below will propagate the change up to SwiftUI
            identifierBinding.wrappedValue = identifier
        }
    }
    
    func makeUIViewController(context: Context) -> ViewController{
        let vc = ViewController()
        vc.delegate = context.coordinator
        return vc
    }
    
    func updateUIViewController(_ uiViewController: ViewController, context: Context) {
        // update the controller data, if needed
    }
    
    // this is very important, this coordinator will be used in `makeUIViewController`
    func makeCoordinator() -> Coordinator {
        Coordinator(identifierBinding: identifier)
    }
}

拼图最后一块就是编写视图控制器代理的代码,以及使用该代理的代码:

protocol ViewControllerDelegate: AnyObject {
    func clasificationOccured(_ viewController: ViewController, identifier: String)
}

class ViewController: UIViewController {
    
    weak var delegate: ViewControllerDelegate?

    ...

    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        ...
  
        print(self.result)

        // let's tell the delegate we found a new clasification
        // the delegate, aka the Coordinator will then update the Binding
        // the Binding will update the State, and this change will be
        // propagate to the Text() element from the SwiftUI view
        delegate?.clasificationOccured(self, identifier: self.result)
    }

3

Swift有多种方法可以使您在视图和对象之间传递数据

例如委托键值观察或者特别针对SwiftUI的属性包装器,如@State、@Binding、@ObservableObject和@ObservedObject。然而,在将数据显示在SwiftUI视图中时,您需要使用属性包装器。

如果您想按照SwiftUI的方式进行操作,您可能需要查看一下@State@Binding属性包装器以及如何使用协调器与您的UIViewControllerRepresentable结构体。向SwiftUI视图添加一个@State属性,并将其作为绑定传递给您的UIViewControllerRepresentable

//Declare a new property in struct MaskDetectionView and pass it to SwiftUIViewController as a binding
@State var string result = ""
...
SwiftUIViewController(resultText: $result)

//Add your new binding as a property in the SwiftUIViewController struct
@Binding var string resultText

那么,您可以将 SwiftUI 视图的一部分(例如,结果字符串)暴露给 UIViewControllerRepresentable。从那里,您可以将其进一步传递给 ViewController,或者参考以下有关协调器的文章:https://www.hackingwithswift.com/books/ios-swiftui/using-coordinators-to-manage-swiftui-view-controllers 在我看来,将相机工作封装在另一个类 ViewController 中已经过时了,使用协调器同样可以很好地完成。以下步骤应该能帮助您启动您的视图控制器:
1. 在 makeUIView 中创建您的视图控制器代码,包括设置 AVKit 对象。 2. 确保将 context.coordinator 作为委托而不是 self。 3. 在 SwiftUIViewController 中创建一个嵌套类 Coordinator,并将该类声明为您的 AVCaptureVideoDataOutputSampleBufferDelegate。 4. 向协调器添加一个属性来保存您的视图控制器对象的实例,并实现初始化程序和 makeCoordinator 函数以使协调器存储对您的视图控制器的引用。 5. 如果到目前为止设置正确,则现在可以在协调器类中实现 AVCaptureVideoDataOutputSampleBufferDelegate 委托函数,并在检测到某些内容并返回结果时更新视图控制器的绑定属性。

非常感谢您的回复。问题是我想从ViewController中的func传递数据到MaskDetectionView,与您所说的相反。有没有办法可以做到这一点? - Yonus
这就是 @Binding 的作用。当您将一个 @State 变量作为绑定传递给其他对象时,状态将在绑定更改时自动更新,反之亦然。SwiftUI 在很大程度上依赖于这个概念,因为每个使用状态变量的视图都会在状态内容更改时自动更新。 - Raphael

1

协议(在其他语言中称为接口)在这种情况下让生活变得更加容易,而且使用起来非常简单。

1- 在适当的位置定义协议

2- 在所需的视图(类、结构体)中实现

3- 将已实现的对象引用传递给调用者类或结构体

示例 - > 如下

//Protocol
protocol MyDataReceiverDelegte {
  func dataReceived(data:String) //any type of data as your need, I choose String
}

struct MaskDetectionView: View, MyDataReceiverDelegte { // implementer struct
   func dataReceived(data:String){
     //write your code here to process received data
     print(data)
   }
var body: some View {
     //your views comes here
     VStack(alignment: .center) {
         SwiftUIViewController(parent:self)
     }
  }
}

//custom view
struct SwiftUIViewController: UIViewControllerRepresentable {
   let parent:MaskDetectionView
   func makeUIViewController(context: Context) -> ViewController{
    return ViewController(delegate:parent)
   }

   func updateUIViewController(_ uiViewController: ViewController, context: Context) {
    
}
}


//caller class
//i omit your code for simpilicity
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
    let delegate: MyDataReceiverDelegte
  init(delegate d: MyDataReceiverDelegte) {
      self.delegate = d
      super.init(nibName: nil, bundle: nil)
   }
required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
    super.viewDidLoad()
    
    //your code comes here
}

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection){
        //your rest of code comes here ,
    delegate.dataReceived("Data you want to pass to parent view")
    }
}

非常感谢!!!你真是个天才...我太开心了。但还有一个问题,现在我的数据在一个空函数里面。我该如何把它拿出来?我想在var body: some View {}中使用它? - Yonus
定义一个 @State 属性,并在 dataReceived(:) 方法中进行赋值,然后将此属性放置在视图的 body 中。请阅读文档,有很多关于 SWIFTUI 和 STATE 变量的文章。 - Mir
代理模式无法工作,因为:1:代理必须是weak的,否则会遇到保留循环的问题;2:您不能将结构体用作代理,因为当分配时,结构体被复制,因此您将无法引用相同的视图。 - Cristik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接