The primary problem here is that UIButton
knows of no method called dismissViewControllerAnimated:completion:
This is a UIViewController
method.
Further more, there is no way to start with a UIView
(or subclass, which your class is a subclass of a subclass of) and get to its view controller. A UIViewController
can get to all its views and subviews though. But there's no guarantee how deeply nested your UIButton
is in the view hierarchy, we'd have to recurse through every view and find one that matches your button's class.
The only real option I can think of here is to create a UIViewController
subclass with a method that looks like this:
- (IBAction)exit:(id)sender {
if (self.navigationController) {
[self.navigationController popViewControllerAnimated:YES];
} else {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
So now this code will get rid of the view controller whether or not it's in a navigation controller (as a note, the if
check may not be good enough--may need some more conditions).
Now, make all of your view controllers a subclass of this view controller. And hook your regular, non-subclassed UIButtons
up to a method that looks like this:
- (IBAction)exit:(id)sender {
[super exit:sender];
}
If you need to do perform any additional code when pushing the button, you can put it around the call to super
. You still have to hook up the button to every view controller... unless you want to give every button a reference to the view controller it needs to dismiss. But this way is less messy and easier to maintain. The view controllers need to be in charge of when they're dismissed or about to present a new view controller. The logic for changing view controllers shouldn't be outside view controller classes.