A_toaster A_toaster - 3 months ago 36
iOS Question

How can you reload a ViewController after dismissing a modally presented view controller in Swift?

I have a first tableViewController which opens up a second tableViewcontroller upon clicking a cell. The second view controller is presented modally (Show Detail segue) and is dismissed with:

self.dismissViewControllerAnimated(true, completion: {})


At this point, the second view controller slides away and reveals the first view controller underneath it. At this point I would like to reload the first view controller. I understand that this may require use of delegate functions but am not sure how to proceed. Thanks in advance for your help!

Answer

I solved it a bit differently since I don't want that dependancy.

And this approach is intended when you present a controller modally, since the presenting controller wont reload when you dismiss the presented.

Anyway solution!

Instead you make a Singleton (mediator)

protocol ModalTransitionListener {
    func popoverDismissed()
}

class ModalTransitionMediator {
    /* Singleton */
    class var instance: ModalTransitionMediator {
        struct Static {
            static let instance: ModalTransitionMediator = ModalTransitionMediator()
        }
        return Static.instance
    }

private var listener: ModalTransitionListener?

private init() {

}

func setListener(listener: ModalTransitionListener) {
    self.listener = listener
}

func sendPopoverDismissed(modelChanged: Bool) {
    listener?.popoverDismissed()
}
}

Have you Presenting controller implement the protocol like this:

class PresentingController: ModalTransitionListener {
//other code
func viewDidLoad() {
    ModalTransitionMediator.instance.setListener(self)
}
//required delegate func
func popoverDismissed() {
    self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
    yourTableViev.reloadData() (if you use tableview)
}
}

and finally in your PresentedViewController in your viewDid/WillDisappear func or custom func add:

ModalTransitionMediator.instance.sendPopoverDismissed(true)