2

在我的 viewController 我有这个功能

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

其中呈现以下 SwiftUIView。

Q 按下 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
    }       
}
4

1 回答 1

0
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
    }
}

或者如果这不起作用,因为您在顶部有不同的视图控制器,或者您需要使用视图生命周期事件(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
    }
}
于 2020-01-30T03:33:26.547 回答