繁体   English   中英

动态将子视图添加到UITableViewCell

[英]Dynamically add subview to UITableViewCell

我正在尝试向UITableViewCell添加一些子视图。 子视图的数量基于我的数据。 当我向下滚动时,子视图消失并且不再显示。 将它们添加到NIB是没有选择的,因为我现在仅是运行时的子视图的数量,并且每个单元的子视图都不同。

在运行时将未知数量的子视图添加到UITableViewCell的正确方法是什么?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"DetailCell";

    DetailCellTableViewCell *cell = (DetailCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DetailCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];


        NSInteger count = [self getMaxSubviews];
        NSInteger y=100;

        for (int i=0; i<count;i++)
        {
            UITextField *dataS = [[UITextField alloc] init];

            dataS.frame=CGRectMake(277, y, 60, 17);

            y=y+17;

            dataS.tag=i+1337;
            dataS.backgroundColor=[UIColor redColor];

            [cell addSubview:dataS];
        }
    }


    if (!useOrigCellFromNib) // Here I can use the original Nib created by IB
    {

        NSString *data = @"Some String";

        [cell.data setText:data];


    }
    else // Use added subviews!
    {

        for (int i=0;i<arrS.count;i++)
        {
            NSManagedObject *s = [arrS objectAtIndex:i];


            UITextView *dataS =[cell viewWithTag:i+1337];

            dataS.text=[NSString stringWithFormat:@"%ld foo", (long)i];
            [cell.data setHidden:YES];

        }

    }

    return cell;
}

1您应该重用单元格,调用tableView.dequeueReusableCellWithIdentifier(“ CellId”)

2获得重用的单元格后,应删除所有以前添加的自定义子视图

3之后,您可以添加新的子视图

关于“我向下滚动子视图消失,不再显示任何内容”,我之前没有看到任何“单元格”变量

if (cell == nil)

因此,您可能不会在此处粘贴重用代码,在这种情况下,滚动后的单元格将不会为nil,而if(cell == nil)下的代码将不会被调用...

就像在重用单元格时提到的Igor一样,您必须先删除它,然后再重新创建子视图。 可能是您不能使用“ loadFromNib”和子类“ UITableViewCell”类在此处创建单元格。

这是一个迅速的例子,但ObjC的逻辑也相同

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let stuffArray = array[indexPath.row]

    var cell = tableView.dequeueReusableCellWithIdentifier("Cell")
    if cell == nil {
        cell = MyCustomCell(initWithDaraArray:stuffArray) // create cell based on array data dynamically

    } else { // even if you have cell you need to refresh it for new data
        cell.refreshDataForDataInArray(stuffArray) // here remove all subviews and create new ones
    }

    return cell
}

单元格的高度可以通过

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let stuffArray = array[indexPath.row]
    return calculatedHeight(stuffArray)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM