Issue to hide swiftUI view in UIHostingController

Hi everybody

I leave it to you because I can not find a solution to my problem, and it may be ******

In the screen (Which is a piece of code from a Swift controller part of my app) you can see that the "showFlux()" function open a swiftUI view, in this view I have a button that calls the "hideFlux()" method, but whatever I put inside nothing happen (But I reach the function), So the problem is just that I don't know how to do

Thanks in advance for your help 😄

Answered by Gernot in 680234022

In the hideFlux function you are creating a new instance of your HostingViewController that is different from the instance you are presenting, so calling dismiss on it does nothing.

Call dismiss() on the presentedViewController, which should be the ViewController you instantiated in the showFlux method.

In general though this is a very brittle pattern. Your code should call the dismiss function from within the ViewController that is to be dismissed, so there is no ambiguity on what should be dismissed.

Also, this is basically UIKit code, if you want to do it in SwiftUI, it is all a bit different, and maybe you shouldn't need to get down to the UIKit layer in the first place.

Accepted Answer

In the hideFlux function you are creating a new instance of your HostingViewController that is different from the instance you are presenting, so calling dismiss on it does nothing.

Call dismiss() on the presentedViewController, which should be the ViewController you instantiated in the showFlux method.

In general though this is a very brittle pattern. Your code should call the dismiss function from within the ViewController that is to be dismissed, so there is no ambiguity on what should be dismissed.

Also, this is basically UIKit code, if you want to do it in SwiftUI, it is all a bit different, and maybe you shouldn't need to get down to the UIKit layer in the first place.

Issue to hide swiftUI view in UIHostingController
 
 
Q