我想动态地将UILabel
添加到我的UITableViewCell
。所以在CellforrowAtIndex
事件中我确实喜欢这个。
static NSString *simpleTableIdentifier = @"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
UILabel *lbl;
[[cell viewWithTag:100] removeFromSuperview];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
}
lbl=[[UILabel alloc] initWithFrame:cell.imageView.frame];
[lbl setText:[NSString stringWithFormat:@"%lu",[[[mutArrayPendingRequests objectAtIndex:indexPath.row] objectForKey:@"RequestItems"] count]]];
[lbl setTag:100];
[lbl setTextAlignment:NSTextAlignmentCenter];
[cell.contentView addSubview:lbl];
但我的问题是当表格加载时我的文字没有设置为UILabel
。但是一旦我滚动它就会加载前三个单元格和底部三个单元格。中间单元格标签未加载。这是什么原因?如何将UILabel
作为自定义视图添加到我的UITableViewCell?
请帮我。
感谢
答案 0 :(得分:1)
试试这个
if (cell == nil){
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier: simpleTableIdentifier];
//create custom labels and button inside the cell view
lbl = [[UILabel alloc] initWithFrame:cell.imageView.frame];
lbl.tag = 100;
lbl.font = [UIFont boldSystemFontOfSize:17.0];
lbl.backgroundColor = [UIColor clearColor];
[lbl setTextAlignment:NSTextAlignmentCenter];
[cell.contentView addSubview: lbl];
}
else {
lbl = (UILabel *)[cell.contentView viewWithTag:100];
}
[lbl setText:[NSString stringWithFormat:@"%lu",[[[mutArrayPendingRequests objectAtIndex:indexPath.row] objectForKey:@"RequestItems"] count]]];
答案 1 :(得分:0)
您为标签设置的框架尺寸,即cell.imageView.frame
无效。
设置一些正确的帧值并检查它是否有效。
lbl=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
答案 2 :(得分:0)
试试这段代码:
static NSString *simpleTableIdentifier = @"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
UILabel *lbl;
[[cell viewWithTag:100] removeFromSuperview];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
}
lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,200 ,40 )];
[lbl setText:[NSString stringWithFormat:@"%lu",[[[mutArrayPendingRequests objectAtIndex:indexPath.row] objectForKey:@"RequestItems"] count]]];
[lbl setTextAlignment:NSTextAlignmentCenter];
[cell.contentView addSubview:lbl];
return cell;
}