我假設你是在談論一個視圖控制器類。如果我理解你是對的,那麼你就要搞砸了。授權是避免子類化的一種方法。當然,你可以繼承這個委託 - 沒問題。但是你想要在超級類中擁有一個表的視圖。你想要一個在其視圖中有另一個表的子類加上超類擁有的表。
這不是不可能的。但從你的子類的角度來看,你的子類擁有兩個表視圖。即使這是可能的。您的視圖控制器是兩個表的代表(不管視圖層次結構中聲明和實例化的位置)。當你現在覆蓋委託和數據源方法時,你的子類必須:
- 確定它正在處理/正在調用哪個表。然後適當地爲這兩個表格服務。
- 確定它正在處理/被調用的桌面。然後適當地提供「自己的」表並調用[super sameMehtod:withSamePamaters]來確保superclas仍然可以提供數據和服務器作爲委託。
哪一個更聰明取決於上下文以及您將要實現的細節。
通過標記表視圖(不使用0作爲標記)或通過比較委託方法的tableView參數與相應的屬性(本例中爲IBOutlets),可以確定調用表的委託的方式。 (在其他情況下,您可以將sender參數與IBOutlets進行比較,但稍後閱讀代碼時,標記可能更容易理解。)
讓我們來看看UITableViewDataSourceDelegat的例子:
你的父類實現:
@interface MySuperTableViewController:UITableViewController <UITableViewDelegate>
// There will be something in here.
// But it inherits self.tableView from UITableViewController anyway. We leave it with that.
@end
@implementation MySuperTableViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// This method creates or re-uses a cell object and sets its properties accordingly.
}
@end
而子類:
@interface MySubTableViewController : MySuperTableViewController // no need to declare the delegate here, it is inherited anyway
@property (weak, nonatomic) IBOutlet UITableView *mySecondTableView; // self.table will be used by the superclass already.
@end
@implementation MySubTableViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == self.table) { // This call refers to the one talbe that is managed by super
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
// This method now creates or re-uses a cell object and sets its properties accordingly.
// You may want to check wether tableView == self.mySecondTableView etc.
}
@end
(這來自從頭開始,而不是語法檢查等。不要指望它馬上正常運行:)
但是...請重新考慮你的班級結構。恐怕你在一些相當不合邏輯的階級體系中迷失了方向。有一個共同的視圖控制器管理兩個talbe,即使沒有這個子類,也沒有錯。在視圖中使用多個表的時候沒有什麼問題,其中每個表都有自己的委託(可以是視圖控制器)。自從iOS 5(或者是它引入了6)以後,我們可以使用UIContainerView來完成這個目的,並且很好地將它構建在IB/storyboard中。
你有沒有正確設置dataSourceDelegate? – Amitg2k12 2013-02-28 12:54:22
@Rohan什麼是正確的方法? – 2013-02-28 12:54:55
我的意思是委託處理程序,這是假設有數據源方法 – Amitg2k12 2013-02-28 12:55:44