2010-08-27 106 views

回答

10

最简单的实现方法是使用Delegates。

在CustomTableCell.h定义的协议是这样的:

@protocol CustomTableCellDelegate <NSObject> 
@required 
- (void)reloadMyTable; 
@end 

下一步是提供一个委托VAR:

@interface CustomTableCell : UITableViewCell { 
    id<CustomTableCellDelegate> delegate; 
} 

@property (assign) id<CustomTableCellDelegate> delegate; 

制作舒尔你合成的委托变量在CustomTableCell .M。

现在你有一个委托定义。有三个剩下的步骤:

当你创建你的,你必须设置该小区委托像

cell.delegate = self; 

制作舒尔你TableViewController实现您CustomTableCellDelegate。如果你这样做,你将被强制执行 - (无效)reloadMyTable在TableViewController:

- (void)reloadMyTable { 
    [self.tableView reloadData]; 
} 

最后一步是从您的CustomTableCell调用此方法是这样的:

if (self.delegate != NULL && [self.delegate respondsToSelector:@selector(reloadMyTable)]) { 
    [delegate reloadMyTable]; 
} 

更多代表团here

简而言之:你定义了一个协议在你的CustomTableViewCell中,由TableViewController实现。如果你发送一个方法消息给你的委托,这个消息将被发送到你的TableViewController。

+0

到目前为止,我不是明确的唯一的事情就是你说:请确保您[R tableviewcontroller实现您的自定义TableCell的委托。 – Brodie 2010-08-27 15:32:19

+0

无视我知道了,谢谢 – Brodie 2010-08-27 16:05:30

+0

@ audience。我可以在哪里放置最后一步的代码?我的意思是应该在哪种方法中调用 – 2013-08-08 06:28:55

2

它是创建通知的最佳方式。在你的tableView中,你必须创建它。这很容易,像这样:

[[NSNotificationCenter defaultCenter] addObserver:self 
            selector:@selector(reloadTableView:) 
             name:@"reloadTable" 
             object:nil]; 

然后,你必须创建方法:

- (void)reloadTableView:(NSNotification *)notif { 
     [self.yourTableName reloadData]; 

}

,不要忘了删除通知:

-(void)dealloc { 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadTable"  object:nil]; 

}

and in yo乌尔定制tableViewCell当你想重装表,则需要:

[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTable" 
               object:nil]; 
+0

比代表解决方案更优雅,代码更少。 +1 – user623396 2014-07-22 12:45:36

+0

我不会说这是最好的方式,更喜欢自己的授权。 – tagy22 2016-04-29 12:57:26

相关问题