2

我有一个 UITableView 并在其中我以以下方式创建了一个自定义 UITableViewCell:

ItemCellController *cell = (ItemCellController *)[tableView dequeueReusableCellWithIdentifier:ContentListsCellIdentifier];
...
cell = [[[ItemCellController alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ContentListsCellIdentifier] autorelease];

我这样做是为了获得 touchesBegan 和 touchesEnded 事件(这样我就可以实现长触摸)。使用 NSLog 我可以看到使用以下代码从 touchesBegan 方法中正确调用了 longTouch:

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(longTouch:) userInfo:nil repeats:YES];

问题是我无法从 longTouch 方法中调用模式窗口。

我尝试了以下方法,但我得到一个 NSInvalidArgumentException -[ItemCellController navigationController]: unrecognized selector sent to instance 错误。

AddItemController *addView = [[AddItemController alloc] initWithNibName:@"AddItemView" bundle:nil];  

UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:addView];
controller.navigationBar.barStyle = UIBarStyleBlack;
[[self navigationController] presentModalViewController:controller animated:YES];
[controller release];

所以问题是,如何从自定义 UITableViewCell 中调用模式窗口。

谢谢

4

2 回答 2

13

navigationController属性存在于UIViewControllers,但UITableViewCell(我猜ItemCellController是它的子类)不是 a UIViewController,因此默认情况下它没有该属性。

有几种方法:

(1) 向您的自定义单元格类型添加一个UIViewController*属性(可能称为它controller),并使用您的 init 方法(例如,)传递一个指向您的控制器的指针initWithController:。然后在您的单元格中,您可以执行:

UINavigationController* navController = [ /* alloc and init it */ ]
[self.controller presentModalViewController:navController animated:YES];

(2) 您的应用程序委托对象可能有一个控制器属性,您可以从代码中的任何位置访问该属性。然后你可以做这样的事情:

MyAppDelegate* myAppDelegate = [[UIApplication sharedApplication] delegate];
[myAppDelegate.controller presentModalViewController:navController
                                            animated:YES];

(3) 这个不太直接,但更灵活。您可以设置您的根控制器(您想要呈现模态视图的那个)以侦听某个通知,并从您的表格单元格中发布该通知。

从根控制器中调用的示例监听代码:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(showModal:)
                                             name:@"show modal"
                                           object:nil];

从表格单元格中调用的示例邮政编码:

NSDictionary* userInfo = [ /* store a handle to your modal controller */ ];
[[NSNotificationCenter defaultCenter] postNotificationName:@"show modal"
                                                    object:self
                                                  userInfo:userInfo];

并且showModal:您的根控制器的方法将使用userInfo包含在其中的方法NSNotification来确定要以模态方式呈现哪个视图控制器。这是更多的工作,但它会自动允许您的任何代码在任何地方呈现模式视图,而无需让它们完全访问根控制器指针。

于 2009-08-12T18:30:41.120 回答
0

它看起来不像你在任何地方设置单元格导航控制器,它似乎不喜欢 [[self navigationController] presentModalViewController:controller animated:YES]; 该行,检查该“自我”对象上的 nagivationController 属性

于 2009-08-12T18:10:49.523 回答