我有一个 SwiftUI 模态视图,我从主 UIKit 视图调用它。我想在我的模式视图中添加一个关闭按钮。据我所知,UIKit 中没有 @State 变量,因此我正在创建一个单独的 SwiftUI 视图来存储我的 @State 变量,但由于某种原因它不起作用。我应该如何解决这个问题?
我在主 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 视图创建模态表,它会以经典方式关闭,但我需要从 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)