簡體   English   中英

從 SwiftUI 導航到 UIViewController

[英]Navigate to UIViewController from SwiftUI

我的初始視圖是使用 SwiftUI 構建的。

我想從這個過渡到 UIViewController 並調用一個可能改變設計的方法,一個例子是隱藏一個 IBOutlet。

這是我目前正在做的事情:

@available(iOS 13.0, *)
struct DetailViewControllerWrapper: UIViewControllerRepresentable {
    typealias UIViewControllerType = DetailViewController

    func makeUIViewController(context: UIViewControllerRepresentableContext<DetailViewControllerWrapper>) -> DetailViewControllerWrapper.UIViewControllerType {

        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let detailViewController: DetailViewController = mainStoryboard.instantiateViewController(withIdentifier: "detailViewController") as! DetailViewController
        detailViewController.someMethod()
        return detailViewController
    }

    func updateUIViewController(_ uiViewController: DetailViewControllerWrapper.UIViewControllerType, context: UIViewControllerRepresentableContext<DetailViewControllerWrapper>) {
        //
    }
}

這是推送到我的 DetailViewController 但我Unexpectedly found nil while implicitly unwrapping an Optional value錯誤Unexpectedly found nil while implicitly unwrapping an Optional value

關於從 SwiftUI 導航到 UIKit/UIViewController 的任何建議?

有工作的一部分UIViewRepresentable呼吁稱之為必需的FUNC makeCoordinator()所引用這里的文檔。 Apple 還提供了有關如何與 UIKit 交互的教程,您可以在此處找到。 Paul Hudson 的另一個教程在這里也可能對您有用。 我使用它的協調器模式在我正在開發的 SwiftUI 應用程序中提供了一個UIImagePickerController 該代碼如下。 您會注意到提供UIImagePickerController所需功能的嵌套類,在您的情況下,我相信您只需要調用 DetailViewController。 我希望這有幫助。 -擔

import SwiftUI

class PhotosData: NSObject, Codable {
    var image: String?

    init(image: String) {
        self.image = image
      }
    }

struct ImagePicker: UIViewControllerRepresentable {
    @Environment(\.presentationMode) var presentationMode
    @Binding var image: UIImage?

class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    let parent: ImagePicker

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let uiImage = info[.originalImage] as? UIImage {
            parent.image = uiImage
        }
        parent.presentationMode.wrappedValue.dismiss()
    }

    init(_ parent: ImagePicker) {
        self.parent = parent
        }
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) { 
    /*Required. Not used*/ 
        }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM