views:

371

answers:

2

If the user taps and holds on a Foo table view cell for 2 seconds, a modal view should be shown. The modal view is also displayed when a new Foo is added to the cell. The modal view's delegate protocol is implemented by the parent UITableView subclass.

My tap and hold detection code is in the Foo UITableViewCell class.

I'm having difficulty referencing the parent tableview's navigation controller to display the modal view.

FooModalViewController *modalController = [[FooModalViewController alloc] initWithNibName:@"FooModalViewController" bundle:nil];
FooTableViewController *tableView = (FooTableViewController *) self.superview;
foo.delegate = tableView;

Seems OK but I'm having problems referencing the navigation controller that contains the tableview.. The code below builds OK but throws an exception - NSOBject DoesNotRecognizeSelector.

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:modalController];
[[tableView.navigationController] presentModalViewController:navigationController animated:YES];

I think that perhaps my design is flawed..?

A: 

The superview of a table view cell object is just a UITableView. It will never be a table view controller (FooTableViewController) — in fact there's no standard way to find the view controller just from the view.

You may try to use tableView.delegate to get the view controller since a table view controller is a delegate of its table view.

[tableView.delegate presentModalViewController:navigationController animated:YES];

Assuming your navigation controller is connected to the app delegate you can also use

YourAppDelegate* del = [UIApplication sharedApplication].delegate;
[del.navCtrler.visibleViewController
    presentModalViewController:navigationController animated:YES];
KennyTM
+1  A: 

The proper way to do this is to give the cell a delegate protocol (such as, - (void)buttonPressedInCell:(UITableViewCell*)cell) and when the button is pressed use that to notify the controller. Then the controller, which will have a reference to the nav controller, can do the appropriate thing.

Steven Canfield
This does seem like the best way, however I implemented it differently in the end. I added parentNavigation/parentTableView properties to the UITableViewCell subclass. These were set by the cell's tableView controller i.e. the parentTableView. I set the delegate of the modal controller to the object referenced by parentTableView, and displayed the new modal view with the object referenced by parentNavigation. Seems to work fine.
NiKUMAN