简体   繁体   中英

Dynamically add subview to UITableViewCell

I'm trying to add some subviews to my UITableViewCell. The number of subviews is based on my data. When I scroll down the subviews disappears and does not show any more. Adding them to the NIB is no option because I only now the number of subviews at runtime and they are different for each cell.

What is the right way to add an unknown number of subviews to a UITableViewCell at runtime?

- (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 you should reuse cells, call tableView.dequeueReusableCellWithIdentifier("CellId")

2 after you get the reused cell, you should delete all previously added custom subviews

3 after that you can add new subviews

about " I scroll down the subviews disappears and does not show any more" I don't see any "cell" variable before

if (cell == nil)

So Probably you do not paste the reuse code here, in this case cells after scrolling will not be nil and the code under the if (cell == nil) will not be called...

Like Igor mentioned when reusing cell you have to remove waht ever you add previousely and re-create subviews. May be you can not use "loadFromNib" and Subclass 'UITableViewCell' class and create your cell there.

This is a example in swift but logic is same for ObjC too

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
}

and cell heights can be adjusted by

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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