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