这里缺少一些关键点,并尝试了多种方法来解决此问题。大多数资源使用现有的ViewController,例如MapKit或UIPicker。在这种情况下,我有一个自定义ViewController,要从中返回UIImage。
我有一个呈现UIViewController的UIViewControllerRepresentable。
ViewController创建一个图像。如何返回图像,以便可以在SwiftUI视图中使用它?
我似乎能找到的最接近的方法是使用协调器设置UIViewControllerRepresentable(这是必需的吗?):
struct CameraPreviewView: UIViewControllerRepresentable {
@Binding var photoTaken: UIImage
func makeCoordinator() -> Coordinator {
return Coordinator(photoTaken: $photoTaken)
}
class Coordinator: NSObject {
@Binding var photoTaken: UIImage
init(photoTaken: Binding<UIImage>) {
_photoTaken = photoTaken
}
}
func makeUIViewController(context: UIViewControllerRepresentableContext<CameraPreviewView>) -> CameraViewController {
let cameraViewController = CameraViewController()
return cameraViewController
}
...
}
但是如何创建“激活”协调器,以便ViewController返回图像?
final class CameraViewController : UIViewController {
// Clearly something goes here, but what?
//var photoTaken: UIImage
// @Binding photoTaken: UIImage
override func viewDidLoad() {
super.viewDidLoad()
}
// A bunch of camera code is here
}
extension CameraViewController: BBMetalCameraPhotoDelegate {
func camera(_ camera: BBMetalCamera, didOutput texture: MTLTexture) {
// This is the image we want returned to SwiftUI
imageView.image = filter.filteredImage(with: texture.bb_image!)
..
}
}
更新 我从UITextField窃取了一个页面,并添加了一个通知和一个侦听器。
现在,我的协调员的工作方式如下:
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
var parent: CameraPreviewView
var photoFromCoordinator = UIImage(named: "test")!
init(_ viewController: CameraPreviewView) {
self.parent = viewController
super.init()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "imageDidChange"), object: nil, queue: OperationQueue.main){(notification) in
print("notice received")
if let image = notification.userInfo?["image"] as? UIImage {
self.photoFromCoordinator = image
}
}
}
}
然后我从Controller触发UIImage:
...
let imageDataDict:[String: UIImage] = ["image": finalImage]
let nc = NotificationCenter.default
nc.post(name: Notification.Name("imageDidChange"), object: nil, userInfo: imageDataDict)
...
所以,我靠近了。该通知在我的协调员内“触发”。
但是现在,如何在SwiftUI视图中提取图像?
到目前为止:
struct ContentView: View {
@State var photoTaken: UIImage?
var body: some View {
//Image(photoTaken)
@State var photoTaken是否从协调器接收数据?如果是,如何在视图中呈现它?