UITableViewCell自动调整高度不起作用

时间:2015-06-01 02:57:20

标签: ios objective-c uitableview uikit

我的表格视图中的单元格不会自动调整其高度以包含内容。我正在使用" Basic"细胞原型的风格。我创建了一个新的测试项目,只包含我的视图控制器和故事板,它有同样的问题。我做错了什么?

RowHeightTestController:

@implementation RowHeightTestController

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Test" forIndexPath:indexPath];

    // Configure the cell...
    cell.textLabel.text = @"Testing";
    cell.textLabel.font = [UIFont systemFontOfSize:60 + indexPath.row];

    return cell;
}

@end

故事板:

Storyboard

我所看到的:

enter image description here

2 个答案:

答案 0 :(得分:1)

尝试设置表的属性:

tableView.estimatedRowHeight = 44.0;
tableView.rowHeight = UITableViewAutomaticDimension;

如果内容更改,则使用通知重新加载表

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(contentSizeCategoryChanged:)
    name:UIContentSizeCategoryDidChangeNotification
    object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
    name:UIContentSizeCategoryDidChangeNotification
    object:nil];
}
// This method is called when the Dynamic Type user setting changes (from the system Settings app)
- (void)contentSizeCategoryChanged:(NSNotification *)notification
{
    [self.tableView reloadData];
}

如需更多关注这个好答案:https://stackoverflow.com/a/18746930/3202193

答案 1 :(得分:1)

为tableView和viewDidLoad创建插座/引用,添加

tableView.estimatedRowHeight = 44.0;
tableView.rowHeight = UITableViewAutomaticDimension;

为此,您必须更新tableView的委托

中的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

不是willDisplay或任何其他代表。

此外,您必须在storyboard / xib中正确设置自动布局约束。

对于简单的单元格视图,如屏幕截图所示, 为UILabel设置以下约束,如下所示:

  • 领导超级视野。
  • 尾随空间到superview
  • 超级视图的顶层空间
  • 超级视图的底部空间
相关问题