swift - 从故事板返回主机控制器到另一个控制器
问题描述
我有一个项目,Storyboard
但现在我正在迁移到SwiftUI
.
我有一个Hosting Controller
控制 del SwiftUI 段,但现在我需要从它返回到另一个控制器Storyboard
。
基本上我可以这样做:Storyboard (Controller 1)
-> HostingController (SwiftUI)
。所以现在我需要返回:HostingController (SwiftUI)
-> Storyboard (Controller 2)
。
解决方案
我喜欢为此使用闭包。我假设您正在展示这样的主机控制器?
let viewController = UIHostingController(rootView: ContentView())
self.present(viewController, animated: true)
dismissSelf
您可以在 SwiftUI View 结构中添加一个闭包:
struct ContentView: View {
var dismissSelf: (() -> Void)?
var body: some View {
Button(action: {
dismissSelf?()
}) {
Text("Return")
}
}
}
这将dismissSelf
在按下按钮时调用。现在,您需要分配dismissSelf
一个代码块来消除UIHostingController
. 你可以这样做:
class ViewController: UIViewController {
@objc func buttonPressed() {
var viewController: UIViewController?
let contentView = ContentView {
/// set the closure (it's a trailing closure, so you don't need to put the `dismissSelf`)
viewController?.dismiss(animated: true, completion: nil)
}
viewController = UIHostingController(rootView: contentView)
if let vc = viewController {
self.present(vc, animated: true, completion: nil)
}
}
/// make the button
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 50, y: 50, width: 80, height: 40))
button.setTitle("Present", for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
view.addSubview(button)
}
}
有一件事有点奇怪。viewController
永远不会为零,但为了避免强制展开,我放入了if let
.
结果:
推荐阅读
- asp.net - 使用 @Html.EditorForModel() 时在 ASP.NET Razor 页面中排序字段
- c++ - for 循环包括指针
- c# - Visual Studio 设计器未找到并呈现由共享资源字典链接的资源
- python - gdaltools 将 geojson 点导出为多点
- docker - Traefik - 无法获取让我们为域加密证书 => acme http 质询超时
- typescript - 在 VS Code 中显示 Typescript 类层次结构
- sql-server - Microsoft SQL Server 删除表和临时表“Bug”问题
- java - 如何使用流编译具有给定属性最大值的所有对象的列表?
- angular - XHR 错误 (404 Not Found) 加载 http://localhost:3002/@kolkov/angular-editor
- sql - 如何从第二个表中仅 INNER JOIN 一行