Reference from UITableViewCell to UITableView to UINavigationController

人盡茶涼 提交于 2020-01-24 01:34:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!