2012-02-14 83 views
1

我創建了一個UITableViewCell子類。在目前使用它的HomeViewController類,我這樣做:如何在IB中重用UITableViewCell子類

@interface: (for HomeViewController) 
@property (nonatomic, assign) IBOutlet UITableViewCell *customCell; 

@implementation: 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CustomTableViewCellIdentifier = @"CustomTableViewCellIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomTableViewCellIdentifier]; 
    if (cell == nil) { 
     UINib *cellNib = [UINib nibWithNibName:@"CustomTableViewCell" bundle:nil]; 
     [cellNib instantiateWithOwner:self options:nil]; 
     cell = self.customCell; 
     self.customCell = nil; 
    } 
    NSUInteger row = [indexPath row]; 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    return cell; 
} 

在CustomTableViewCell.xib,我的文件的所有者是HomeViewController我出口從文件的所有者到CustomTableViewCell連接。所有這一切都很好。

現在我想要另一個名爲DetailViewController的UIViewController的子類來使用這個單元格。我的文件的所有者對象已被使用。我不太熟悉創建其他對象以重用此單元格。有人可以解釋我在這種情況下需要做什麼嗎?謝謝。

回答

4

首先,每次都不要創建一個UINib對象。創建一次並重用它。它將運行得更快。

其次,它看起來像文件的所有者,你接線的唯一財產是customCell。如果這就是你所需要的,那麼根本就不要連接一個連接。相反,請確保單元格是筆尖中第一個或唯一的頂級對象(通過將其設置爲筆尖輪廓的「對象」部分中的第一個頂級對象)。那麼你可以這樣訪問它:

+ (UINib *)myCellNib { 
    static UINib *nib; 
    static dispatch_once_t once; 
    dispatch_once(&once, ^{ 
     nib = [UINib nibWithNibName:@"CustomTableViewCell" bundle:nil]; 
    }); 
    return nib; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CustomTableViewCellIdentifier = @"CustomTableViewCellIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomTableViewCellIdentifier]; 
    if (cell == nil) { 
     NSArray *topLevelNibObjects = [self.class.myCellNib instantiateWithOwner:nil options:nil]; 
     cell = [topLevelNibObjects objectAtIndex:0]; 
    } 

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    return cell; 
}