Reputation: 61
I have a tableview and I set autolayout to the cells, so one cell's height might be 50, another ones might be 120. I need to show max 2 cells, so if count > 2, then cell count = 2, else it equals to the cells count.
My problem is resizing UITableView height according to the each cell size. How can I properly set UITableView height constraint value?
I hope I could explain what I want, if you have any question, please ask me
Upvotes: 0
Views: 1827
Reputation: 3288
Try the below code it works out
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Upvotes: 0
Reputation: 411
If your ios target is >= 8, then you can make your tableview cell adjust without much pain.
//provide the estimated height of your cell row over here
self.tableView.estimatedRowHeight = 60
self.tableView.rowHeight = UITableViewAutomaticDimension
Don't forget to put top,bottom,left,right constraints for all the views inside content view of the cell.
Upvotes: 0
Reputation: 29161
Have a look at the code I posted on this StackOverflow article.
You simply add a static function to your UITableViewCell
, which "measures itself", then you store that in a "row height" variable.
+(CGSize)preferredSize
{
static NSValue *sizeBox = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Assumption: The XIB file name matches this UIView subclass name.
NSString* nibName = NSStringFromClass(self);
UINib *nib = [UINib nibWithNibName:nibName bundle:nil];
// Assumption: The XIB file only contains a single root UIView.
UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject];
sizeBox = [NSValue valueWithCGSize:rootView.frame.size];
});
return [sizeBox CGSizeValue];
}
(You would think that by now, in 2016, Apple would have provided us with a simpler way of doing this...)
Upvotes: 1
Reputation: 3508
Try to store UITableViewCell heights in an array at the time of calculating height.
If you are manually calculating height, store the height in array. if you are adapting cell height automatically, get the cell and then its height and store it in an array
Upvotes: 0
Reputation: 2187
Don't set the height explicitly. Use this:
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
Upvotes: 1
Reputation: 11
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 50
} else {
return 120
}
}
Upvotes: 1