2010-08-27 108 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

相關問題