【发布时间】:2015-06-08 18:34:55
【问题描述】:
我正在尝试制作一个包含 X 个单元格的 UITableView。每个单元格上可以有 2 到 20 多个视图,但视图的数量不应该是硬编码的。
所以第一个 UITableViewCell 可能只有 3 个标签,而第二个 UITableViewCell 可能有 6 个标签。
我该如何实现呢?我很难让内容出现,并且 UITableView 的高度正确。
我目前的解决方案是在一个方法中生成内容(因为我无法在init方法中生成),然后在将信息传递给单元格后将子视图添加到contentView。到目前为止,这会产生不好的结果(单元格的高度计算不正确)。
这是 UITableViewCell 生成内容的方法。
- (void) generateContent
{
// Simplifying the code, but this section will be hooked up with a property on the UITableViewCell to generate the content
UIView *pmv = [[[NSBundle mainBundle] loadNibNamed:@"PortalModuleView"
owner:self
options:nil] objectAtIndex:0];
UIView *pmv2 = [[[NSBundle mainBundle] loadNibNamed:@"PortalModuleView"
owner:self
options:nil] objectAtIndex:0];
// add the views
[self.contentView addSubview:pmv];
[self.contentView addSubview:pmv2];
// add in some constraints
}
这是 UITableView 的数据源
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// static NSString *CellIdentifier = @"Cell";
ViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
[cell generateContent];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
问题是单元格没有生成我想要的内容(我认为这是由于高度不正确;约束取决于高度是否正确)。我认为主要原因只是在生成视图之前单元格无法生成正确的高度。
我尝试过使用reloadRowsAtIndexPath,但它并不能解决所有行的问题。
【问题讨论】:
-
添加一些你尝试过的示例代码,以及你卡住的问题
-
你的单元格高度的逻辑是什么?为什么要硬编码?
-
这只是一个硬编码的起点;我的印象是,因为我使用的是
estimatedHeight,它会自动为我更正单元格的高度(我在单元格内使用自动布局)。我刚刚意识到我可以事先计算 UITableView 单元格的高度 -
哦,我明白了,为此使用 UITableViewAutomaticDimension。但是计算高度并将其传递给 heightForRowAtIndexPath:这将解决单元格高度问题。我认为你需要调用 [cell generateContent];在 cellForRowAtIndexPath 中:在返回单元格之前
-
如果你预先计算了高度,它就可以工作。我认为它不能仅通过使用 UITableViewAutomaticDimension 起作用(我在返回单元格之前确实调用了
cell generateContent),并且行高为 44。还有什么可以尝试的吗?我可以预先计算高度,但如果我不必这样做,它会让我的生活更轻松
标签: ios uitableview