【问题标题】:UITableViewCell auto-sizing height not workingUITableViewCell 自动调整高度不起作用
【发布时间】:2015-06-01 02:57:19
【问题描述】:

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

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

故事板:

我所看到的:

【问题讨论】:

    标签: ios objective-c uitableview uikit


    【解决方案1】:

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

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

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

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
    

    不是willDisplay 或任何其他代表。

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

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

    • 引导空间到superview。
    • 超级视图的尾随空间
    • 超级视图的顶部空间
    • 超级视图的底部空间

    【讨论】:

      【解决方案2】:

      尝试设置表格的属性:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 2015-03-25
        • 1970-01-01
        • 2016-08-19
        • 2011-03-05
        • 1970-01-01
        相关资源
        最近更新 更多