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

前端 未结 3 1756
既然无缘
既然无缘 2021-02-02 17:25

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 d

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-02 17:55

    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)
    

提交回复
热议问题