I have a UIViewController that contains a UITableView.
This UIViewController is being displayed in a UIPopoverController.
I was having this same problem and none of the answers I found worked. I cobbled together that I think works well.
I have an array in my initWithCoder that holds my values. I simply run this code:
- (id)initWithCoder:(NSCoder *)aDecoder
{
//Popover Choices
_importantChoices = [NSMutableArray array];
[_importantChoices addObject:@"Bakery"];
[_importantChoices addObject:@"Beverage Dry Mix"];
[_importantChoices addObject:@"Beverage RTD"];
[_importantChoices addObject:@"Crisps"];
[_importantChoices addObject:@"Meat"];
[_importantChoices addObject:@"Supplements"];
//Calculate size of Popover
self.clearsSelectionOnViewWillAppear = NO;
NSInteger rowsCount = [_importantChoices count];
NSInteger singleRowHeight = [self.tableView.delegate tableView:self.tableView
heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
NSInteger totalRowsHeight = rowsCount * singleRowHeight;
CGFloat largestLabelWidth = 0;
for (NSString *tmp in _importantChoices) {
CGSize labelSize = [tmp sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20.0f]}];
if (labelSize.width > largestLabelWidth) {
largestLabelWidth = labelSize.width;
}
}
CGFloat popoverWidth = largestLabelWidth + 100; //Add a little padding to the width
self.preferredContentSize = CGSizeMake(popoverWidth, totalRowsHeight);
return self;
}