【发布时间】:2014-07-01 08:03:29
【问题描述】:
我的UITableView 中有自定义单元格,根据字符串的值,我想在单元格中添加一个UILabel。
这是我的单元格代码,
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary * tmpDictn = [tableAry objectAtIndex:indexPath.section];
NSString * typeStr = [tmpDictn objectForKey:@“DocumentType”];
NSString * cellIdentifier = @"TestCell";
TestCell *cell = (TestCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell){
cell = [[TestCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
if ([typeStr isEqualToString:@“Text”]) {
UILabel * textLbl = [[UILabel alloc] init];
textLbl.backgroundColor=[UIColor clearColor];
textLbl.textColor=[UIColor lightGrayColor];
textLbl.userInteractionEnabled=NO;
textLbl.numberOfLines = 0;
textLbl.font = [UIFont fontWithName:@“Helvetica" size:16];
[textLbl setFrame:CGRectMake(30, 20, 250, 25)];
textLbl.text= [NSString stringWithFormat:@"%@ %i",[splitAry objectAtIndex:i],indexPath.section];
[cell addSubview:textLbl];
}
}
return cell;
}
我的UITableView 包含 5 个单元格(动态)。只有第一个单元格应该有这个标签(这也根据文本改变)。此代码在第一个单元格中添加 UILabel,但还在第 3 和第 5 个单元格中添加 UILabel。
我检查了它的相同UILabel 创建了 1 次,并添加到了第 1、第 3 和第 5 个单元格中。而“文本”仅在表格中排在第一位。
【问题讨论】:
-
是 typStr 值是常量还是动态
-
您正在使用 dequeueReusableCellWithIdentifier 因此,一旦您将标签添加到单元格,它将在下次重用时出现。您不会在任何地方删除标签,只是添加。我建议继承 UITableViewCell,创建自己的自定义单元格并根据需要进行配置。
-
如果你滚动表格视图,标签会改变它的位置。原因是在单元可重用的情况下,您对所有单元使用相同的单元标识符。对那些你想要的带有标签的单元格使用不同的单元格标识符,其余的使用不同的单元格标识符。
标签: ios iphone uitableview custom-cell