registerNib用于具有多个视图的XIB中的UITableViewCell

时间:2014-07-11 18:59:01

标签: ios objective-c uitableview

我已经成功地使用registerNib在XIB中定义UITableViewCell的UI,其中只有一个UITableViewCell原型。

为了封装,是否可以在其中安装带有多个UITableViewCell的XIB,并且仍然能够使用registerNib加载正确的单元?

如果是这样,如何在代码中识别XIB中所需的单元原型?

我目前在tableView的VDL中这样做,这很好用:

[self.tableView registerNib:[UINib nibWithNibName:@"LogoCell" bundle:[NSBundle mainBundle]]
     forCellReuseIdentifier:CellId];

有没有办法指定我们想要使用的XIB中的哪个单元原型?

提前致谢。

2 个答案:

答案 0 :(得分:5)

In the interest of encapsulation, would it be possible to have an XIB with more than one UITableViewCell in it and still be able to load the proper cell using registerNib?

没有

答案 1 :(得分:1)

实际上,这是可能的。如果您有某种方法来区分XIB中的视图(标签,自定义类等),那么您甚至不需要注册笔尖 - 您只需要这样做:

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger cellIndex = 12345;
    NSString *cellIdentifier = @"MyAwesomeCell";

    // dequeue cell or, if it doesn't exist yet, create a new one from the nib
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MyNibWithLotsOfCustomCells" owner:self options:nil];
        NSUInteger index = [topLevelObjects indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
            // if you distinguish the views by class
            return [obj isMemberOfClass:NSClassFromString(cellIdentifier)];
            // if you distinguish the views by tag
            return [(UIView*)obj tag] == cellIndex;
        }];
        cell = topLevelObjects[index];
    }

    // etc.
}

使用dequeueReusableCellWithIdentifier:而非dequeueReusableVellWithIdentifier:forIndexPath:非常重要(差异在this thread中说明)。