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

前端 未结 3 1758
既然无缘
既然无缘 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条回答
  •  清歌不尽
    2021-02-02 18:04

    You can simply reaload your data in viewDidAppear:, but that might cause the table to be refreshed unnecessarily in some cases.

    A more flexible solution is to use protocols as you have correctly guessed.

    Let's say the class name of your first tableViewController is Table1VC and the second one is Table2VC. You should define a protocol called Table2Delegate that will contain a single method such as table2WillDismissed.

    protocol Table2Delegate {
        func table2WillDismissed()
    }
    

    Then you should make your Table1VC instance conform to this protocol and reload your table within your implementation of the delegate method.

    Of course in order for this to work, you should add a property to Table2VC that will hold the delegate:

    weak var del: Table2Delegate?
    

    and set its value to your Table1VC instance.

    After you have set your delegate, just add a call to the delegate method right before calling the dismissViewControllerAnimated in your Table2VC instance.

    del?.table2WillDismissed()
    self.dismissViewControllerAnimated(true, completion: {})
    

    This will give you precise control over when the table will get reloaded.

提交回复
热议问题