2015-12-16 67 views
0

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

什么是一个未知的数子视图在运行时添加到一个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; 
} 
+0

调整在哪里ü申报细胞? –

+0

根据您的评论更新。 Fogotten粘贴声明部分的单元格。 – lueda

回答

0

像代码伊戈尔在重复使用单元格时提到,必须先删除以前添加并重新创建子视图。 也许你不能使用“loadFromNib”和Subclass'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) 
} 
0

1,你应该重用细胞,称之为tableView.dequeueReusableCellWithIdentifier( “CELLID”)

2你会得到重用的小区后,你应该删除所有以前添加的自定义后子视图

3你可以添加新的子视图

关于“我向下滚动子视图中消失,并且不显示任何” 我不

前看到任何“细胞”变量
if (cell == nil) 

所以也许你不粘贴在这里重用代码,在这种情况下,细胞滚动不会是零后下如果(细胞==零)将不会被称为...

+0

你说得对。忘记粘贴必要的申报部分细胞。 – lueda

+0

我也不明白useOrigCellFromNib变量在你的代码中是如何改变的? – Igor

+0

你从哪儿拿arrS数组?请提供完整的原始代码 – Igor

相关问题