121

I have a theoretic question. Now İ'm reading Apple's ViewController guide.

They wrote:

When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it. Although there are several techniques for notifying the presenting view controller that its presented view controller should be dismissed, the preferred technique is delegation.

But I can't explain, why I have to create a protocol in presented VC and add delegate varible, create delegate method in presenting VC for dismissing presented VC, instead of a simple call in presented view controller method

[self dismissViewControllerAnimated:NO completion:nil]?

Why is the first choice better? Why does Apple recommend it?

jeet.chanchawat
  • 5,228
  • 5
  • 31
  • 57
nikitahils
  • 1,332
  • 2
  • 10
  • 8

14 Answers14

127

I think Apple are covering their backs a little here for a potentially kludgy piece of API.

  [self dismissViewControllerAnimated:NO completion:nil]

Is actually a bit of a fiddle. Although you can - legitimately - call this on the presented view controller, all it does is forward the message on to the presenting view controller. If you want to do anything over and above just dismissing the VC, you will need to know this, and you need to treat it much the same way as a delegate method - as that's pretty much what it is, a baked-in somewhat inflexible delegate method.

Perhaps they've come across loads of bad code by people not really understanding how this is put together, hence their caution.

But of course, if all you need to do is dismiss the thing, go ahead.

My own approach is a compromise, at least it reminds me what is going on:

  [[self presentingViewController] dismissViewControllerAnimated:NO completion:nil]

[Swift]

  self.presentingViewController?.dismiss(animated: false, completion:nil)
foundry
  • 30,849
  • 8
  • 87
  • 124
  • 28
    It should be noted that using `presentingViewController` is mostly useless as it will refer to the `UINavigationController` if `self` is embedded in one. In which case, you won't be able to get the `presentingViewController` at all. Yet, `[self dismissViewControllerAnimated:completion]` still works in that case. My suggestion would be to continue to use that until Apple fixes it. – memmons Mar 06 '14 at 00:03
  • 4
    I love that this answer is still totally relevant 3 years later. – user1021430 Jul 01 '17 at 01:34
  • 1
    Something else to consider is that a view controller doesn't know how it was displayed. It might have been presented, pushed onto a navigation controller, part of a tab bar controller etc. Using the delegate allows the "presenting" view controller to "dismiss" the view controller using the inverse of whatever method was used to present it. – David Smith Aug 02 '19 at 17:15
56

Updated for Swift 3

I came here just wanting to dismiss the current (presented) View Controller. I'm making this answer for anyone coming here with the same purpose.

Navigation Controller

If you are using a navigation controller, then it is quite easy.

Go back to the previous view controller:

// Swift
self.navigationController?.popViewController(animated: true)

// Objective-C
[self.navigationController popViewControllerAnimated:YES];

Go back to the root view controller:

// Swift
self.navigationController?.popToRootViewController(animated: true)

// Objective-C
[self.navigationController popToRootViewControllerAnimated:YES];

(Thanks to this answer for the Objective-C.)

Modal View Controller

When a View Controller is presented modally, you can dismiss it (from the second view controller) by calling

// Swift
self.dismiss(animated: true, completion: nil)

// Objective-C
[self dismissViewControllerAnimated:YES completion:nil];

The documentation says,

The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.

So it works for the presented view controller to call it on itself. Here is a full example.

Delegates

The OP's question was about the complexity of using delegates to dismiss a view.

To this point I have not needed to use delegates since I usually have a navigation controller or modal view controllers, but if I do need to use the delegate pattern in the future, I will add an update.

Community
  • 1
  • 1
Suragch
  • 364,799
  • 232
  • 1,155
  • 1,198
53

This is for view controller reusability.

Your view controller shouldn't care if it is being presented as a modal, pushed on a navigation controller, or whatever. If your view controller dismisses itself, then you're assuming it is being presented modally. You won't be able to push that view controller onto a navigation controller.

By implementing a protocol, you let the parent view controller decide how it should be presented/pushed and dismissed/popped.

Michael Enriquez
  • 2,480
  • 19
  • 13
7

try this:

[self dismissViewControllerAnimated:true completion:nil];
FelixSFD
  • 5,456
  • 10
  • 40
  • 106
6

In my experience, it comes in handy when you need to dismiss it from any ViewController you want and perform different tasks for each viewcontroller that dismisses it. Any viewController that adopts the protocol can dismiss the view in it's own way. (ipad vs iphone, or passing different data when dismissing from different views, calling different methods when dismissing, etc..)

Edit:

So, to clarify, if all you ever want to do is dismiss the view, I see no need to setup the delegate protocol. If you need to do different things after you dismiss it from different presenting view controllers, It would be your best way to go using the delegate.

jhilgert00
  • 5,363
  • 2
  • 35
  • 53
  • but if i don't need "passing different data when dismissing from different views, calling different methods when dismissing, etc.." can i do one little call in presented view controller method -- [self dismissViewControllerAnimated:NO completion:nil]? – nikitahils Jan 31 '13 at 23:25
  • Letting the presenter dismiss the presented view, makes it obvious that the presenter is in fact ready and handling the return to the foreground: the execution sequence is easy to follow, and the responsibility of any UI update is implicitly clear. – Johan Dec 26 '15 at 10:31
3

Swift 3.0 //Dismiss View Controller in swift

self.navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
Pranit
  • 747
  • 8
  • 18
2

Quote from View Controller Programming Guide, "How View Controllers Present Other View Controllers".

Each view controller in a chain of presented view controllers has pointers to the other objects surrounding it in the chain. In other words, a presented view controller that presents another view controller has valid objects in both its presentingViewController and presentedViewController properties. You can use these relationships to trace through the chain of view controllers as needed. For example, if the user cancels the current operation, you can remove all objects in the chain by dismissing the first presented view controller. Dismissing a view controller dismisses not only that view controller but also any view controllers it presented.

So on one hand it makes for a nice balanced design, good de-coupling, etc... But on the other hand it's very practical, because you can quickly get back to a certain point in navigation.

Although, I personally would rather use unwinding segues than try to traverse backwards the presenting view controllers tree, which is what Apple talks about in this chapter where the quote is from.

svena
  • 2,729
  • 18
  • 24
2

One point is that this is a good coding approach. It satisfies many OOP principles, eg., SRP, Separation of concerns etc.

So, the view controller presenting the view should be the one dismissing it.

Like, a real estate company who gives a house on rent should be the authority to take it back.

1

In addition to Michael Enriquez's answer, I can think of one other reason why this may be a good way to protect yourself from an undetermined state:

Say ViewControllerA presents ViewControllerB modally. But, since you may not have written the code for ViewControllerA you aren't aware of the lifecycle of ViewControllerA. It may dismiss 5 seconds (say) after presenting your view controller, ViewControllerB.

In this case, if you were simply using dismissViewController from ViewControllerB to dismiss itself, you would end up in an undefined state--perhaps not a crash or a black screen but an undefined state from your point of view.

If, instead, you were using the delegate pattern, you would be aware of the state of ViewControllerB and you can program for a case like the one I described.

Mayur
  • 33
  • 5
1

Swift

let rootViewController:UIViewController = (UIApplication.shared.keyWindow?.rootViewController)!

        if (rootViewController.presentedViewController != nil) {
            rootViewController.dismiss(animated: true, completion: {
                //completion block.
            })
        }
Kaustubh Khare
  • 2,540
  • 1
  • 25
  • 40
Rishi Chaurasia
  • 490
  • 3
  • 16
1

I like this one:

        (viewController.navigationController?.presentingViewController
            ?? viewController.presentingViewController
            ?? viewController).dismiss(animated: true)
mbi
  • 403
  • 5
  • 12
0

If you are using modal use view dismiss.

[self dismissViewControllerAnimated:NO completion:nil];
ErasmoOliveira
  • 1,397
  • 2
  • 19
  • 39
  • How does this answer the question: *"Why is the first choice better? Why does Apple recommend it?"* – jww Feb 20 '17 at 03:08
0

This is a lot of baloney. Delegation is fine when it is needed but if it makes the code more complex -- and it does -- then there needs to be a reason for it.

I'm sure Apple has its reasons. But it is clearer and more concise to simply have the presented VC do the dismiss unless there is a true reason for doing otherwise and no one here as of today has presented one that I can see.

Protocols are excellent when they're needed but object oriented design was never about having modules communicating unnecessarily with each other.

Tom Love (co-developer of Objective C) once commented that Objective C was "elegant", "small", "crisp" and "well-defined" (when comparing with C++). Easy for him to say. Delegation is a useful feature that seems to have been over-used "just because", and while I like working in the language, I dread the idea of felling compelled to use unnecessary syntax to make things more complex than they have to be.

Andrew Li
  • 47,104
  • 10
  • 106
  • 132
RegularExpression
  • 3,473
  • 2
  • 23
  • 34
  • It may save you some code initially, but your approach will cause you many head aches as your code base grows. You should understand object oriented principles such as separation of concerns, otherwise you might as well code your whole application into one big file. – Werner Altewischer Nov 27 '17 at 15:12
-4

You can Close your super view window

self.view.superview?.window?.close()

MR.Code
  • 1
  • 2