Change height of UITableView programmatically

2020-05-07 02:39发布

问题:

I have a UITableView and I'd like to change its height programmatically depending on the number of cells contained in it.

Can you help me?

回答1:

You can use this code

self.yourTableView.frame = CGRectMake(x,y,width,noOfCell*heightOfOneCell);


回答2:

You can observe tableView.contentSize changes and bind the value to the frame, keep in mind you might run into memory issues since table view won't recycle cells



回答3:

Did you tried sizeToFit or sizeThatFits:?

CGRect tFrame = tableView.frame;
tFrame.size.height = MIN([tableView sizeThatFits: CGSizeMake(tFrame.size.width,
                                                             CGFLOAT_MAX)].height,
                         MaximumTableHieght);
tableView.frame = tFrame;

Or try this (I don't remember which was working for me).

CGRect tFrame = tableView.frame;
tFrame.size.height = MIN(tableView.contentSize.height,
                         MaximumTableHieght);
tableView.frame = tFrame;