Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone - access uitableviewcontroller from uitableviewcell

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!

like image 228
adam Avatar asked May 06 '09 09:05

adam


4 Answers

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.

like image 59
gklka Avatar answered Nov 04 '22 23:11

gklka


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`
like image 31
bureaucoconut Avatar answered Sep 18 '22 15:09

bureaucoconut


This should do the trick:

UITableView *tv = (UITableView *) self.superview.superview;
UITableViewController *vc = (UITableViewController *) tv.dataSource;
like image 27
kareman Avatar answered Nov 04 '22 22:11

kareman


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.

like image 7
Jane Sales Avatar answered Nov 04 '22 21:11

Jane Sales