在我的TableVIew中,我用Xib加载自定义单元格,对于CellForIndexPath的每个条目,单元格被重新创建。如何避免细胞再造??
我是IPhone新手,请帮助我。您可以使用标准方法来缓存先前创建的单元格。在你的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
方法中,你应该使用下一个方法创建单元格:
static NSString *CellIdentifier = @"YourCellIdentifier";
cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// create (alloc + init) new one
[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
cell = myCell;
self.myCell = nil;
}
// using new cell or previously created
不要忘记你将在内存中存储所有可见单元格的对象。当您滚动表格时,这些单元格将被重用。
例如,如果你有10个可见的细胞,那么细胞将== nil 10次,你将分配+init它们。当您向下滚动时,将创建另一个单元格(因为将有11个可见单元格),并且对于12个单元格,您将重用为第一个单元格创建的单元格。
正如@rckoenes所说,不要忘记在IB中设置相同的单元格CellIdentifier
。
希望我讲清楚了
当你从Nib加载视图时,每次当cellForRowAtIndexPath调用时,它都会分配内存,所以每次重新绘制单元格而不是分配内存是更好的方法。下面的例子可能对你有帮助。
自定义单元格中的参数化crate标签。像
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
lblusername=[[UILabel alloc]initWithFrame:CGRectMake(70, 10, 150, 25)];
lblusername.backgroundColor=[UIColor clearColor];
lblusername.textColor=[UIColor colorWithRed:33.0/255.0 green:82.0/255.0 blue:87.0/255.0 alpha:1.0];
[contentview addSubview:lblusername];
[lblusername release];
}
return self;
}
并使用下面列出的代码调用自定义单元格。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
LeaderboardCustomeCell *cell = (LeaderboardCustomeCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[LeaderboardCustomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.lblusername.text=@"Hello";
}