模式中的关闭按钮

模式中的关闭按钮

本文介绍了从 UIKit 调用的 SwiftUI 模式中的关闭按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have got a SwiftUI modal view which I am calling from main UIKit view. I want to add a dismiss button to my modal view. As I can tell, there is no @State variables in UIKit, so I am creating a separate SwiftUI view to store my @State variable but for some reason it is not working. How should I fix this?

我在主 ViewController 中的代码:

My code inside 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 结构:

StateInUIKitHack struct:

struct stateInUIKitHack: View {
     @State var modalIsPresented = false

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

在 MoodCardView.swift 里面我有:

Inside MoodCardView.swift I have:

 @Binding var isPresented: Bool

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

And if I create my modal sheet from another SwiftUI View the classical way it dismisses OK, but I need to create it from the UIKit view.

推荐答案

这里是可能的方法的演示.使用 Xcode 11.4/Playground 测试

Here is a demo of possible approach. Tested with 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()

这篇关于从 UIKit 调用的 SwiftUI 模式中的关闭按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:41