I have a structure like this....
UITableViewController -> UITableViewCell -> UIView
I need the UIView
to access a HashTable (NSMutableDictionary
) in the UITableViewController
Is there a way to access the ViewController simply from the ViewCell (using [ViewCell superview] obviously won't work) ....Do I need to go down through the AppDelegate using [[UIApplication sharedApplication] delegate]
?
Thanks!
You can create a category for this:
@implementation UITableViewCell (FindTableViewController)
- (id<UITableViewDataSource>)tableViewController
{
UIView *view = self;
while (!(view == nil || [view isKindOfClass:[UITableView class]])) {
view = view.superview;
}
return ((UITableView *)view).dataSource;
}
@end
Then you can simply access self.tableViewController
from the cell itself (assuming you have included this category). You may need to cast it to your table view controller's class tho.
Some modification from Kare Morstol answer :
The hierarchy of tableviewcell is in iOS 5.0(my test version)
cell.superview = tableview
cell.superview.superview = UIViewControllerWrapperView
So, use cell.superview to get tableview. And the tableview and tableviewController has a relation of delegate, dataSource in default.
You can get tableviewController reference by tableview.delegate
or tableview.dataSource
.
UITableView *tableView = cell.superview;
UITableViewController *tableViewController = tableView.delegate; // or tableView.dataSource`
This should do the trick:
UITableView *tv = (UITableView *) self.superview.superview;
UITableViewController *vc = (UITableViewController *) tv.dataSource;
I usually maintain a weak reference from my UIView to my UIViewController if I need one, usually by creating a method something like this:
-(MyView*)initWithController:(CardCreatorViewController*) aController andFrame:(CGRect)aFrame
{
if (self = [super initWithFrame:aFrame])
{
controller = aController;
// more initialisation here
}
return self;
}
You could also use a delegate pattern if you want a more decoupled solution. I tend to think this is overkill for a view and its controller, but I would use it with a system of controllers and subcontrollers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With