如何在IB中重用UITableViewCell子类

时间:2012-02-14 20:01:49

标签: iphone uitableview

我创建了一个UITableViewCell子类。在当前使用它的HomeViewController类中,我这样做:

@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子类来使用这个单元格。我的文件所有者对象已被使用。我不是非常熟悉创建其他对象以重用此单元格。有人可以解释在这种情况下我需要做什么吗?感谢。

1 个答案:

答案 0 :(得分:4)

首先,不要每次都创建一个UINib对象。创建一次并重用它。它运行得更快。

其次,看起来你正在连接的文件所有者的唯一属性是customCell。如果这就是您所需要的,那么根本不连接连接就更简单了。相反,确保单元格是nib中的第一个或唯一的顶级对象(通过使其成为nib轮廓的Objects部分中的第一个顶级对象)。然后你可以像这样访问它:

+ (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;
}