【发布时间】:2014-06-23 09:55:20
【问题描述】:
我有一个包含 UILabel 的自定义 UITableViewCell。我正在尝试动态调整 UILabel 的宽度以正确显示它包含的文本。我知道如何调整 UILabel 的大小,但我注意到 UITableViewCell 在使用 UITableViewCellAccessoryDisclosureIndicator 的附件类型时调整 UILabel 大小的方式有一些奇怪的行为。单元格设置如下:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 145, 31)];
label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
label.backgroundColor = [UIColor blueColor]; // So that I can see the frame
[cell.contentView addSubview:label];
然后我有一个典型的 cellForRowAtIndexPath 实现如下:
- (UITableViewCell *)tableView:(UITableView *)_table_view cellForRowAtIndexPath:(NSIndexPath *)_index_path
{
static NSString *cell_id = @"Cell";
CustomTableViewCell *cell = (CustomTableViewCell *)[_table_view dequeueReusableCellWithIdentifier:cell_id];
if(!cell)
{
cell = [[[CustomTableViewCell alloc] initWithReuseIdentifier:cell_id] autorelease];
}
// Resize UILabel frame. Note: assume that CustomTableViewCell has label property
cell.label.frame = CGRectMake(15, 0, 290, 31);
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
return(cell);
}
第一次分配 CustomTableViewCell 时一切正常。即使 UILabel 的宽度是 290,它也会被缩小以适当地适合单元格,因为单元格需要空间来显示披露指示符。当我从表格视图切换(例如切换到不同的选项卡等)时会出现问题。当我回到表格视图时,不会分配 CustomTableViewCell,因为它是从 dequeueReusableCellWithIdentifier 函数返回的。当 UILabel 通过设置框架来调整大小时,单元格似乎不再尊重 UILabel 应该调整大小以适应披露指示符的事实,并导致 UILabel 与披露指示符重叠。
当出现以下情况时,UITableViewCell 似乎无法正确自动调整子视图的大小:
- 使用从 dequeueReusableCellWithIdentifier 返回的 UITableViewCell
- 通过设置框架调整作为 contentView 子视图的 UIView 的大小
- UITableViewCell 正在使用 UITableViewCellAccessoryDisclosureIndicator 作为附件。
有没有人知道为什么会发生这种情况以及解决它的方法?谢谢!
【问题讨论】:
-
尝试创建自定义 UITableViewCell 并重新定义
layoutSubviews方法,例如:stackoverflow.com/questions/2366802/… -
离题(与您的问题无关):1. 使用 ARC 2. 使用
return cell;而不是return(cell); -
签出
accessoryType他们会从你的单元格中占用额外的空间,它会调整你的标签大小。我建议在分配accessoryType后更改框架。 -
我想我可能已经明白了。在自动调整大小以补偿附件之后,似乎 contentView 和 UILabel 的帧大小都在 cellForRowAtIndexPath 函数之外发生了变化。因此,如果我想动态调整 UILabel 的大小,我必须在任何时间点将它基于 contentView.frame.size.width。我想我没有意识到 UIViews 的帧大小实际上在自动调整大小的过程中发生了变化,但回想起来,这是有道理的。这有意义吗?其他人有更好的解决方案吗?
-
我有类似的问题,还没有得到解决方案。你是什么意思'基地'?从超级视图中删除?
标签: ios objective-c uitableview frame