UITableView的错误值:iOS8的rowHeight

我用来创build一个矩形(至less到iOS7)的代码是

CGRect rect = [cTableView frame]; rect.origin.y += [cTableView rowHeight]; searchOverlayView = [[BecomeFirstResponderControl alloc] initWithFrame:rect]; 

在iOS7上, cTableView (一个UITableView的实例)返回44 。 用iPhone 5s在iOS8中testing返回-1

为什么发生这种情况? 为了使我的应用程序与iOS7向后兼容,需要使用哪些正确的代码?

Apple将iOS8中的默认行高更改为声明为-1 UITableViewAutomaticDimension 。 这意味着您的表格视图被设置为自动细胞高度计算。

您将需要实现autoLayout(推荐)或实现新的委托方法: heightForRowAtIndexPath 。 下面是关于自动布局的一个很好的问题: 在UITableView中使用自动布局来实现dynamic单元格布局和可变的行高

似乎无论如何,你是有效的硬编码44(旧的默认),所以你可以做到这一点(不推荐)。

这使我奋斗了几个小时。 我最终硬编码值为44:

 self.tableView.rowHeight = 44; 

对于实现heightForRowAtIndexPath,我们不希望在执行heightForRowAtIndexPath时出现性能损失,因为表中的所有行都是相同的高度,并且在运行时不会更改(每次显示表时都会调用一次)。

在这种情况下,我继续在XIB中设置“Row Height”,并在需要rowHeight时使用以下iOS 8友好代码(它也适用于iOS 7及以下版本)。

 NSInteger aRowHeight = self.tableView.rowHeight; if (-1 == aRowHeight) { aRowHeight = 44; } 

这允许你在XIB中自由地编辑行高,并且即使苹果将来修复了这个bug /特性,并且XIB设置行高= 44停止返回为-1,也可以工作。

如果您不小心将IB的行高从44更改为其他值(如40),则自动单元大小计算失败。 你欠我3个小时,苹果。

我对这个问题的解决scheme:

 @interface MCDummyTableView () <UITableViewDataSource, UITableViewDelegate> @end @implementation MCDummyTableView - (instancetype) initWithFrame:(CGRect)frame style:(UITableViewStyle)style { frame = (CGRect){ 0, 0, 100, 100 }; self = [super initWithFrame:frame style:style]; if(!self) return self; self.dataSource = self; self.delegate = self; [self registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"]; return self; } - (NSInteger) numberOfSections { return 1; } - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (UITableViewCell*) cellForRowAtIndexPath:(NSIndexPath*)indexPath { /* UITableView doesn't want to generate cells until it's in the view hiearchy, this fixes that. However, if this breaks (or you don't like it) you can always add your UITableView to a UIWindow, then destroy it (that is likely the safer solution). */ return [self.dataSource tableView:self cellForRowAtIndexPath:indexPath]; } - (UITableViewCell*) tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { return [self dequeueReusableCellWithIdentifier:@"CELL"]; } - (CGFloat) defaultRowHeight { return [self cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]].frame.size.height; } @end 

我真的不喜欢硬编码的东西。 我使用这个类来caching应用程序中的默认单元格高度。

还有一点需要考虑的是,如果基于现有视图尺寸计算高度,则可以在viewDidLayoutSubviews之前调用heightForRowAtIndexPath方法。

在这种情况下,请覆盖viewDidLayoutSubviews ,然后重新计算所有可见单元格的frame.size.height值。