如何回收从XIB创build的UITableViewCell对象?

我想使用XIB创build自定义的UITableViewCell,但我不知道如何使用UITableViewController的排队机制来回收它。 我怎样才能做到这一点?

伙计们,这个问题的目的是按照常见问题自我回答,虽然我喜欢真棒回答。 有一些upvotes,对待自己的啤酒。 我问这是因为一个朋友问我,我想把它放在StackOverflow上。 如果你有任何贡献,一切手段!

如果你使用iOS 5,你可以使用

[self.tableView registerNib:[UINib nibWithNibName:@"nibname" bundle:nil] forCellReuseIdentifier:@"cellIdentifier"]; 

那么每当你打电话时:

 cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"]; 

tableview将加载笔尖并给你一个单元格,或为你出列一个单元格!

该笔尖只需要一个在其内部定义了单个tableviewcell的笔尖!

创build一个空的笔尖,并添加表格单元格作为第一个项目。 在检查器中,可以在Interface Builder中添加reuseIdentifierstring。

要在代码中使用单元格,请执行以下操作:

 - (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *reuseIdentifier = @"blah"; //should match what you've set in Interface Builder UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; if (cell == nil) { cell = [[[NSBundle mainBundle] loadNibNamed:@"YourTableCellNib" owner:nil options:nil] objectAtIndex:0]; } //set up cell return cell; } 

还有一种方法是为单元格创build一个插口,并使用控制器作为文件的所有者加载单元格笔尖,但实际上这更容易。

如果你想能够访问你已经添加到笔尖单元格的子视图,给他们独特的标签,并访问它们[单元格viewWithTag:x];

如果你想能够在单元格上设置自定义的属性,你需要创build一个自定义的UITableViewCell子类,然后在InterfaceBuilder中将其设置为你的nib的类,并且当你将它们出队时将UITableViewCell强制转换为你的自定义子类上面的代码。

要使用XIB设置自定义的UITableViewCell,您必须做以下几件事:

  • 在您的标题中设置一个IBOutlet
  • 在Interface Builder中configuration表格视图单元格
  • tableView:cellForRowAtIndexPath:加载XIB tableView:cellForRowAtIndexPath:
  • configuration它像任何其他单元格

所以…让我们在头文件中设置一个IBOutlet。

 @property (nonatomic, retain) IBOutlet UITableViewCell *dvarTorahCell; 

不要忘记在实现文件中综合它。

 @synthesize dvarTorahCell; 

现在,我们来创build和configuration单元格。 您需要注意Cell Identifier和IBOutlet,如下所示:

在这里输入图像说明

现在在代码中,将XIB加载到您的单元格中,如下所示:

在这里输入图像说明

请注意Interface Builder中的单元标识符与下面的代码中显示的匹配。

然后,继续前进,像其他人一样configuration您的手机。

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { [[NSBundle mainBundle] loadNibNamed:@"YUOnlineCell" owner:self options:nil]; cell = dvarTorahCell; dvarTorahCell = nil; } //configure your cell here. 

请注意,在访问子视图(如标签)时,您现在需要通过标记来引用它们,而不是通过属性名称(如textLabeldetailTextLabel来引用它们。

在这里你可以做什么:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { YourCustomeCell *cell = (YourCustomeCell *)[tableView dequeueReusableCellWithIdentifier:CellClassName]; if (!cell) { NSArray *topLevelItems = [cellLoader instantiateWithOwner:self options:nil]; cell = [topLevelItems objectAtIndex:0]; } return cell; } 

其中.h中的cellLoader定义如下:

 UINib *cellLoader; 

在.m中如下所示(例如在初始化期间):

 cellLoader = [[UINib nibWithNibName:CellClassName bundle:[NSBundle mainBundle]] retain]; 

CellClassName是在.m中定义的,如下所示(也是你的xib的名字)。

 static NSString *CellClassName = @"YourCustomeCell"; 

不要忘记在xib创build的单元格中也使用stringCellClassName

更多的信息,我build议你阅读这个奇妙的教程创build一个自定义的uitableviewcell-in-ios-4 。

希望能帮助到你。

PS我build议你使用UINib因为是一个优化的方法来加载xib文件。