一旦设备旋转,我在 UITableView 中显示具有正确高度的 UITableViewCells 时遇到问题。最初加载表格视图时,所有行都具有正确的大小,如下图所示:
但是,当我将设备旋转到横向模式时,我得到的行比我想要的要短,因此,部分视图背景是可见的,请参见此处:
再次将手机转回纵向模式时,行大小比第一次加载视图时更大,因此底部单元格看起来更小,并且文本看起来不在单元格中居中,请参见此处:
这是我用于行高计算的方法和变量:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
CGFloat statusBarWidth = [UIApplication sharedApplication].statusBarFrame.size.width;
CGFloat navigationBarHeight = self.navigationController.navigationBar.frame.size.height;
CGFloat rowHeight;
NSUInteger numberOfRows = self.orderedCategories.count;
if (orientation == UIDeviceOrientationPortrait) {
rowHeight = ((screenHeight - navigationBarHeight - statusBarHeight) / numberOfRows);
NSLog(@"portrait: %f", rowHeight);
} else {
rowHeight = ((screenWidth - navigationBarHeight - statusBarWidth) / numberOfRows);
NSLog(@"landscape: %f", rowHeight);
}
return rowHeight;
}