UITableView dynamic cell heights only correct after some scrolling(UITableView 动态单元格高度仅在一些滚动后正确)
问题描述
我有一个 UITableView 和一个自定义 UITableViewCell 在情节提要中使用自动布局定义.该单元格有几个多行 UILabels.
I have a UITableView with a custom UITableViewCell defined in a storyboard using auto layout. The cell has several multiline UILabels.
UITableView 似乎可以正确计算单元格高度,但对于前几个单元格的高度没有在标签之间正确划分.滚动一点后,一切都按预期工作(即使是最初不正确的单元格).
The UITableView appears to properly calculate cell heights, but for the first few cells that height isn't properly divided between the labels.
After scrolling a bit, everything works as expected (even the cells that were initially incorrect).
- (void)viewDidLoad {
    [super viewDidLoad]
    // ...
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"TestCell"];
    // ...
    // Set label.text for variable length string.
    return cell;
}
是否有什么我可能遗漏的东西,导致自动布局在最初几次无法完成其工作?
Is there anything that I might be missing, that is causing auto layout not to be able to do its job the first few times?
我创建了一个示例项目来演示这种行为.
I've created a sample project which demonstrates this behaviour.
推荐答案
我不知道这是否有明确的记录,但是在返回单元格之前添加 [cell layoutIfNeeded] 可以解决您的问题.
I don't know this is clearly documented or not, but adding [cell layoutIfNeeded] before returning cell solves your problem.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"TestCell"];
    NSUInteger n1 = firstLabelWordCount[indexPath.row];
    NSUInteger n2 = secondLabelWordCount[indexPath.row];
    [cell setNumberOfWordsForFirstLabel:n1 secondLabel:n2];
    [cell layoutIfNeeded]; // <- added
    return cell;
}
这篇关于UITableView 动态单元格高度仅在一些滚动后正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:UITableView 动态单元格高度仅在一些滚动后正确
 
				
         
 
            
        基础教程推荐
- LocationClient 与 LocationManager 2022-01-01
- 如何使 UINavigationBar 背景透明? 2022-01-01
- 如何使用 YouTube API V3? 2022-01-01
- Android文本颜色不会改变颜色 2022-01-01
- “让"到底是怎么回事?关键字在 Swift 中的作用? 2022-01-01
- :hover 状态不会在 iOS 上结束 2022-01-01
- 使用 Ryzen 处理器同时运行 WSL2 和 Android Studio 2022-01-01
- Android ViewPager:在 ViewPager 中更新屏幕外但缓存的片段 2022-01-01
- 在 iOS 上默认是 char 签名还是 unsigned? 2022-01-01
- 固定小数的Android Money Input 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				