Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to dismiss the modal view controller

Tags:

xcode

ios

swift

Unable to dismiss modal view controller and return back to the root view controller. Animation did show but still pop out the current view controller.

I am developing app without using storyboard and i would like to dismiss the current modal view controller and back to root view controller.

is there any proper way to do this ?

My Root Controller is Navigation Controller While my modal View Controller is UIViewController. Is it the root cause for not working?

Modal View Controller (PlayerViewController)

func handleBack() {
    self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}

FeedCell.swift in HomeController (FeedCell.swift)

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let playerViewController = PlayerViewController()
    playerViewController.modalPresentationStyle = .overCurrentContext
    self.window?.rootViewController?.present(playerViewController, animated: true, completion: nil)
}

AppDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    let layout = UICollectionViewFlowLayout()
    window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))

    UINavigationBar.appearance().barTintColor = UIColor.rgb(red: 230, green: 32, blue: 31)

    // get rid of black bar underneath navbar
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().setBackgroundImage(UIImage(),for: .default)

    application.statusBarStyle = .lightContent

    let statusBarBackgroundView = UIView()
    statusBarBackgroundView.backgroundColor = UIColor.rgb(red: 194, green: 31, blue: 31)

    window?.addSubview(statusBarBackgroundView)
    window?.addConstraintsWithFormat(format: "H:|[v0]|", views: statusBarBackgroundView)
    window?.addConstraintsWithFormat(format: "V:|[v0(20)]", views: statusBarBackgroundView)

    return true
}

"Tapped" did showed but dismiss not working enter image description here

like image 653
aznelite89 Avatar asked Nov 21 '25 08:11

aznelite89


1 Answers

If you want to dismiss the current view controller that was presented as modal, you should invoke the one that presented the view controller and tell it to dismiss the presented view controller:

self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)

presentingViewController:

The view controller that presented this view controller.

like image 170
OhadM Avatar answered Nov 22 '25 21:11

OhadM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!