我需要在UITableView中显示以下结构。我在MainTableViewCell中创建了childTableView。同时,两个tableviewCell都需要根据描述计算动态高度,我的做法是,在MainTableViewCell中写下以下代码来计算动态高度。
[
{
"schedule_type": "appointment",
"schedule_id": “1234”,
“schedule_desc”: “This is long text. Needs to mange with dynamic height in UILabel”,
“activities” : [
{
“activity_id” : “12”,
“activity_desc” : “long description”
},
{
“activity_id” : “123”,
“activity_desc” : “long description”
},
{
“activity_id” : “121”,
“activity_desc” : “long description”
}
]
},
{
"schedule_type": "appointment",
"schedule_id": “1234”,
“schedule_desc”: “This is long text. Needs to mange with dynamic height in UILabel”,
“activities” : [
{
“activity_id” : “12”,
“activity_desc” : “long description”
},
{
“activity_id” : “123”,
“activity_desc” : “long description”
},
{
“activity_id” : “121”,
“activity_desc” : “long description”
}
]
}
]
为了计算动态高度,我的做法是,在MainTableViewCell里面写了以下代码。
self.childTable.dataSource = self;
self.childTable.delegate = self;
[self.childTable reloadData];
[self.childTable layoutIfNeeded];
self.childViewHeightConstraint.constant = self.childTable.contentSize.height
但是当我把断点放在计算childTableView高度时,它给我单元格的默认值,即44。所以,它没有根据内容更新,我的整个单元格看起来很乱。
我的方法是正确的,还是有其他更好的方法在tableview中实现上述数据?
如果你把你的设置代码放在view did load中,它将不会工作。你需要在视图中添加 self.childViewHeightConstraint.constant = self.childTable.contentSize.height
凌驾于 viewDidLayoutSubviews
. 如果你的约束条件设置正确,例如,灵活,你将有正确的值,用于 self.childTable.contentSize.height
.