[英]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中添加了子视图(这意味着子视图是预定义的),则它可以工作。
有什么方法可以动态地将子视图添加到单元格吗? 还是我将代码放在错误的位置?
感谢您的所有回复。
这真令人尴尬。 问题是我错误地配置了标签属性,使标签文本颜色为白色,但是以某种方式scrollView背景也为白色。 所以我看不到标签,但实际上它们已经在那儿了。
所有答复都很有帮助,但是@Shebin的回答给了我检查颜色的提示,因此我认为我应该将他的回答标记为最佳。
您需要在子视图上添加适当的约束。 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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.