我的问题如下:我将一个可变数组分配给cellForRowAtIndexPath
,以便它在单元格中显示每个数组对象。到目前为止,细胞按预期显示。现在我希望在第一个单元格中显示(根据条件)UILabel
,以便其他可变数组对象将移动到第二个单元格,第三个,等等。
问题是,当我测试那个条件时,它是真的,UILabel
显示在第一个单元中,第一个对象。实际上,两个元素在同一个单元格中,这不是我所期望的。我想(当条件为真时)移动所有元素,以便它们将从第二个单元格显示,以便将第一个单元格留给UIlabel
。
我的相关代码没有给出我的期望,是:
- (UITableViewCell*)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"any-cell"];
// Add and display the Cell
cell.tag = [indexPath row];
NSLog(@"cell.tag= %i",cell.tag);
//test the condition, if it's ok, then add the label to the first cell
if ([self isNoScoreLabelDisplayed] && cell.tag==0) {
UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 220, 50)];
[lbl setBackgroundColor:[UIColor greenColor]];
[cell addSubview:lbl];
}
cell.tag = [self isNoScoreLabelDisplayed]?[indexPath row]+1:[indexPath row];//here i wanted to shift the tags in case the condition is true, so that all the elements will be displayed from the second cell. But seems not doing what i want :(
//
if (indexPath.row < cellList.count) {
[cell addSubview:[cellList objectAtIndex:[indexPath row]]];//cellList is the mutable array from which i get all the elements to display in the cells
}else{
[cell addSubview:nextButton];
}
return cell;
}
我的逻辑中缺少什么?提前完成。
答案 0 :(得分:1)
您正在将indexPath.row直接与模型索引相关联,而它们应该为“title”单元格进行偏移。
if (indexPath.row && (indexPath.row - 1) < cellList.count) {
[cell addSubview:[cellList objectAtIndex:indexPath.row - 1]];
} else {
答案 1 :(得分:1)
我会为此使用两个单元格标识符,一个用于LabelCell,另一个用于常规ArrayCell,这将清除u,并且您将不会获得带有标签和对象的单元格。
另外我真的不知道你在做什么,但它看起来像每次都将subViews添加到单元格中,但是你不会在任何地方删除它们。不要忘记细胞被重复使用......
答案 2 :(得分:1)
您好,在我看来,您检查标签条件,然后在mutablearray中添加相同的对象,因为您的indexPath.row == 0&lt;第一行的cell.count。
cell.tag = [self isNoScoreLabelDisplayed]?[indexPath row]+1:[indexPath row];//here i wanted to shift the tags in case the condition is true, so that all the elements will be displayed from the second cell. But seems not doing what i want :(
所以上面的代码只是设置你的cell标签等于indexpath.row + 1如果你必须显示标签但是下面的代码(记住第一次indexPath.row == 0,所以即使你显示了label)添加相同的数组对象: - )
if (indexPath.row < cellList.count)
答案 3 :(得分:0)
您可以将标签的文本作为容器中的第一个元素插入并检查。这样您就可以节省索引偏移和代码进一步复杂性的任何需求。
E.g。
[cellList insertObject:@"Label name" atIndex:0];
if ([cell tag] == 0) {
// add required label
}
else {
// do whatever you do for your standard cells, getting them with [cellList objectAtIndex:[indexPath row]];
}