Incorrect row height returned when iOS device rotated
I'm having an issues with displaying UITableViewCells with the correct height in a UITableView once the device is rotated. When the table view is initially loaded the rows all have the correct size as you can see on the image below:
However, when I rotate the device to landscape mode I get shorter rows than I would like and consequently, parts of the view's background are visible, see here:
When turning the phone back to portrait mode again, the row sizes are larger then when the view was loaded for the first time and as a result, the bottom cell seems smaller, and the text does not look centred in the cell, see here:
This is the method and variables I'm using for row height calculation:
- (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;
}
I don't have a definite answer, but here are a few things to consider:
1) why are you calling [self.tableview setNeedsDisplay] inside tableView:heightForRowAtIndexPath? If you need to reset the display here, there's probably something wrong with your overall logic.
2) what about moving the calculation code out to the didRotateFromInterfaceOrientation: method? Then call reloadData when you're done. Store the height in an instance variable, and just return that in tableView:heightForRowAtIndexPath:.
2) does this code get run after the rotation. Try logging out the different constants and double check the math by hand. That may give you a better idea of what's going on. There may be a timing issue--for example, you may be getting the status bar height before the rotation occurs, instead of after it occurs.
链接地址: http://www.djcxy.com/p/58384.html上一篇: 旋转后UITableViewCell图像不能调整大小
下一篇: iOS设备旋转时返回的行高不正确