如何动态地将子视图添加到表格视图单元格

How to add subviews to a tableview cell dynamically

我在 IB 中创建了一个自定义表格视图单元格。我添加一个滚动视图作为单元格 contentView 的子视图,并在 tableview 单元格子类中创建 IBOutlet,并建立连接。我的问题是,我想动态地向单元格添加子视图,但是当我在代码中这样做时,没有任何反应。单元格渲染成功,但是scrollView没有显示(上面没有子视图)。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // deque the cell
    // create some label depending on the MODEL object
    // (this is done by code, not in IB. because the label is content-based)
    // we don't know how many labels in advance
    [cell.scrollView addSubview: label];  // not working !!
    ...
    return cell;
}

但是如果我在 IB 中添加子视图(这意味着子视图是预定义的),它就可以工作。

有什么方法可以动态地将子视图添加到单元格吗?或者我把代码放错地方了?

您需要在子视图上添加适当的约束。 UIScrollView 的可滚动大小是根据其子视图的约束计算的。请确保正确添加对单元格内容视图的约束。

如果您没有像标签等那样对子视图设置约束,则使用它的 intrinsicContentSize

试试这个

UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, 130, 30)];
label1.text = @"any text";
label1.textColor = [UIColor redColor];
label1.backgroundColor = [UIColor greenColor];
[cell addSubview:label1];// first try adding to cell

如果您需要添加为 cell.scrollView

的子视图
NSLog(@"scrollView %@",cell.scrollView);//it should not be nil

检查 scrollView 内容大小和框架

对于动态字符串,这对您也有帮助

NSString *string = @"This is the text";
CGSize stringsize = [string sizeWithFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, stringsize.width+30/*you have to adjust 30 as u required*/, 30)];
label1.text = string;
label1.textColor = [UIColor redColor];
label1.backgroundColor = [UIColor greenColor];
cell.scrollView.contentSize = CGSizeMake(label1.frame.size.width+30/*you have to adjust 30 as u required*/, label1.frame.size.height);
[cell.scrollView addSubview:label1];

感谢您的所有回复。

这真是尴尬。问题是我错误配置了标签 属性,将标签文本颜色设置为白色,但不知何故 scrollView 背景也是白色。所以我看不到标签,但实际上它们已经在那里了。

所有的回答都有帮助,但是@Shebin的回答给了我检查颜色的提示,所以我认为我应该将他的回答标记为最佳。