gpt4 book ai didi

swiftui - 如何从 Viewcontroller 中关闭 swiftUI?

转载 作者:行者123 更新时间:2023-12-05 07:20:43 25 4
gpt4 key购买 nike

在我的 viewController 中我有这个功能

...{
let vc = UIHostingController(rootView: SwiftUIView())
present(vc, animated: true, completion: nil)
}

呈现以下 SwiftUIView。

问如何在按下 CustomButton 时关闭 SwiftUIView?

struct SwiftUIView : View {
var body: some View {
CustomButton()
}
}

struct CustomButton: View {

var body: some View {
Button(action: {
self.buttonAction()
}) {
Text(buttonTitle)
}
}

func buttonAction() {
//dismiss the SwiftUIView when this button pressed
}
}

最佳答案

struct CustomButton: View {

var body: some View {
Button(action: {
self.buttonAction()
}) {
Text(buttonTitle)
}
}

func buttonAction() {
if let topController = UIApplication.topViewController() {
topController.dismiss(animated: true)
}
}
}

extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.windows.first { $0.isKeyWindow }?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}

或者如果这不起作用,因为您在顶部有不同的 View Controller ,或者如果您需要使用 View 生命周期事件(onDisappear 和 onAppear 不适用于 UIHostingController)。您可以改用:

final class SwiftUIViewController: UIHostingController<CustomButton> {
required init?(coder: NSCoder) {
super.init(coder: coder, rootView: CustomButton())
rootView.dismiss = dismiss
}

init() {
super.init(rootView: CustomButton())
rootView.dismiss = dismiss
}

func dismiss() {
dismiss(animated: true, completion: nil)
}

override func viewWillDisappear(_ animated: Bool) {
rootView.prepareExit()
}

override func viewDidDisappear(_ animated: Bool) {
rootView.doExit()
}
}

struct CustomButton: View {
var dismiss: (() -> Void)?

var body: some View {
Button(action: dismiss! ) {
Text("Dismiss")
}
}
func prepareExit() {
// code to execute on viewWillDisappear
}
func doExit() {
// code to execute on viewDidDisappear
}
}

关于swiftui - 如何从 Viewcontroller 中关闭 swiftUI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57392915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com