从 UIKit 调用的 SwiftUI 模式中的关闭按钮

Dismiss button in SwiftUI modal called from UIKit

我有一个从 UIKit 主视图调用的 SwiftUI 模式视图。我想在我的模态视图中添加一个关闭按钮。据我所知,UIKit 中没有@State 变量,因此我创建了一个单独的 SwiftUI 视图来存储我的@State 变量,但由于某种原因它不起作用。我应该如何解决这个问题?

我在 main ViewController 中的代码:

var hack = StateInUIKitHack()
hack.modalIsPresented = true
let vc = UIHostingController(rootView: MoodCardView(isPresented: hack.$modalIsPresented, entryIndex: entryIndex, note: moodEntries[entryIndex].note ?? ""))
self.present(vc, animated: true, completion: nil)

StateInUIKitHack 结构:

struct stateInUIKitHack: View {
     @State var modalIsPresented = false

    var body: some View {
        Text("Hello, World!")
    }
} 

里面MoodCardView.swift我有:

 @Binding var isPresented: Bool

如果我从另一个 SwiftUI 视图创建我的模态 sheet,它会以经典方式关闭,但我需要从 UIKit 视图创建它。

这是一个可能的方法演示。使用 Xcode 11.4 / Playground

进行测试

完整的游乐场代码:

import UIKit
import SwiftUI
import PlaygroundSupport

class ViewModel {
    var closeAction: () -> Void = {}
}

struct ModalView: View {
    var vm: ViewModel

    var body: some View {
        VStack {
            Text("I'm SwfitUI")
            Button("CloseMe") {
                self.vm.closeAction()
            }
        }
    }
}

class MyViewController : UIViewController {

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let button = UIButton(type: .roundedRect)
        button.setTitle("ShowIt", for: .normal)
        button.addTarget(self, action: #selector(MyViewController.showModal(_:)), for: .touchDown)

        view.addSubview(button)

        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        self.view = view
    }

    @objc func showModal(_ : Any?) {
        let bridge = ViewModel()
        let vc = UIHostingController(rootView: ModalView(vm: bridge))
        bridge.closeAction = { [weak vc] in
            vc?.dismiss(animated: true)
        }
        self.present(vc, animated: true, completion: nil)
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

backup