问题
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..?
回答1:
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.
回答2:
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];
来源:https://stackoverflow.com/questions/2437482/reference-from-uitableviewcell-to-uitableview-to-uinavigationcontroller