How to redraw my view in SWIFT?

2019-08-16 00:46发布

问题:

On my iPad app, I have a UIViewController with a button that open a modalView.

@IBAction func showPostCommentViewController(sender: AnyObject){

    let modalView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("PostCommentViewController") as! PostCommentViewController
    modalView.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
    modalView.modalPresentationStyle = UIModalPresentationStyle.FormSheet
    modalView.delegate=self
    self.presentViewController(modalView, animated: true, completion: nil)
}

When I close the modalView with dismissViewControllerAnimated, I would like "refresh" my view controller (because I added new content). But as the modal view is a "formsheet" style, viewDidAppear or viewWillAppear aren't called.

I tried to use setNeedsDisplay, but it doesn't work.

I don't know how to do.

回答1:

This would be a perfect use case for the delegate pattern.

1) define a protocol within PostCommentViewController.

protocol PostCommentVCInformationDelegate {
    func hasDismissedPostCommentViewController(controller:PostCommentViewController)
}

2) Set a delegate variable within PostCommentViewController

var delegate: PostCommentVCInformationDelegate?

3) When you dismiss PostCommentViewController, you will call delegate?.hasDismissedPostCommentViewController(self)

This will send information back to the presenting VC.

4) Now we have our presenting View Controller conform to this protocol.

class ViewController: UIViewController, PostCommentVCInformationDelegate

5) When presenting the modal View:

modalView.delegate = self

6) Finally, we implement:

func hasDismissedPostCommentViewController(controller: PostCommentViewController) {
    //Update
}