我有一个导入两个 TableViewControllers 的 ViewController。
我有在这些子类中执行的委托/数据源方法,但是无论如何 ViewController 是否可以判断每个 TableView 何时执行了委托方法 didSelectRowAtIndexPath 等方法,或者我是否必须在每个 tableviewcontroller 中添加方法以轮询单元格是否已经被选中?
谢谢!
我有一个导入两个 TableViewControllers 的 ViewController。
我有在这些子类中执行的委托/数据源方法,但是无论如何 ViewController 是否可以判断每个 TableView 何时执行了委托方法 didSelectRowAtIndexPath 等方法,或者我是否必须在每个 tableviewcontroller 中添加方法以轮询单元格是否已经被选中?
谢谢!
那么你可以创建一个@protocol
这样的:
@protocol MyChildViewControllerDelegate<NSObject>
@optional
- (void)tablView:(UITableView *)tv didSelectRowInChildViewControllerAtIndexPath:(NSIndexPath*)indexPath;
@end
现在MyChildViewControllerDelegate
在类中ChildViewController
创建一个属性@synthesize
,如下所示:
@property(assign, nonatomic) id<MyChildViewControllerDelegate> delegate;
现在,当在父类中创建一个实例时,ChildViewController
通过如下方式分配委托self
:
ChildViewController *ch = [[ChildViewController alloc] initWithBlahBlah];
ch.delegate = self;
并实施MyChildViewControllerDelegate
方法。
现在,当您收到任何UITableViewDelegate
回调时,ChildViewController
通过委托告诉您的父类。
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)iPath
{
[delegate tablView:tView didSelectRowInChildViewControllerAtIndexPath:iPath];
}
而不是自己制作,你MyChildViewControllerDelegate
也可以使用苹果提供的UITableViewDelegate
(你觉得舒服)。
希望能帮助到你 :)
您可以定义自己的通知,例如“MyDidSelectRowAtIndexPathNotification”,并使您的主视图控制器成为此通知的观察者:
#define kMyDidSelectNotification @"MyDidSelectRowAtIndexPathNotification"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myDidSelectAction:) name:kMyDidSelectNotification object:nil];
然后,在您的实现中tableView:didSelectRowAtIndexPath
,您可以简单地为所有观察者触发此通知:
[[NSNotificationCenter defaultCenter]
postNotificationName:kMyDidSelectNotification object:nil];
您可以在此处看到UITableViewCell
,如果需要,您可以在通知中传递 或其他对象。您的通知处理程序(myDidSelectAction:
在这种情况下)接收一个NSNotification
对象,该对象将包含您在 postNotification 操作中传递的对象。
在我看来,虽然协议也可以工作,但设置起来更复杂。
查看Notification Center的文档。