I have a custom class myCustomClass
which is a subclass of UITextField
. (I'm going to call myCustomClass
in a viewControllers
class.)
In myCustomClass
, I'm trying to check what kind of viewController
the class that called it is. (UIViewController
, UITableViewController
etc.)
I tried:
if ([self.superview.nextResponder isKindOfClass[UIViewController class]]) {
NSLog(@"View Controller");
} else if ([self.superview.nextResponder isKindOfClass[UITableViewController class]) {
NSLog(@"TableView Controller");
}
I only get a result if the superclass
is a viewController
. So I did the following:
NSLog(@"%@", self.superview.nextResponder);
Results
UIViewController Class - ViewController
UITableViewController Class - UITableViewCell
How can I check if it's a UITableViewController?
For your specific case, you can use
[self.superView isMemberOfClass:[UITableViewCell class]]
to check if your custom view is inside a table view cell, which (unless you are using tableViewCell in an unusual way!) means that it's being called from a UITableViewController.More generally, if you wanted to find out the containing view controller, you can recursively walk up the responder chain to find the containing viewController as in the second answer in this post: Get to UIViewController from UIView?
It's also important to note that there is a difference between
isKindOfClass:
andisMemberOfClass:
isKindOfClass
returns YES if 'the receiver is an instance of given class or an instance of any class that inherits from that class.'isMemberOfClass
returns YES if ' the receiver is an instance of a given class.'Therefore, your UITableViewController, which inherits from UIViewController, will answer YES to
isKindOfClass:[UIViewController class]
, will yourif
statement to act unexpectedly. (Though in the example it also didn't work correctly because you still needed to walk up the responder chain further).So, if you in fact are comparing a UIViewController to a UITableViewController use
-isMemberOfClass
and your logic in the example would work as expected.