Is it possible to subclass a UITableView and make it the intrinsic content size for its height depending on the number of cells?

I only want mine UITableView

to be as tall as it should be, as it floats above the main one UIViewController

view

. If I hardcoded the height to 200 and theres' only one cell in the table, it looks silly.

I know that in a view controller I could control the table view and determine its height based on the number of cells it has, but height is a property of the view, and for MVC it ​​doesn't make the controller actively control the view's height.

Is it possible to have a subclass UITableView

and define an internal height based on the number of cells it stores? So with Auto Layout I could add a subclass to my view, specify its width, center it vertically, and possibly define a "less than or equal" height constraint to keep it less than 200pt. But for the most part, the internal size of the view content automatically determines the height of the view?

It will look like it UILabel

can be centered horizontally and vertically some distance from left and right and it will grow and shrink automatically automatically.

Can I do this with a subclass UITableView

?

+3


source to share


3 answers


This can be done easily if the table view uses the contentSize property to "know" how tall it should be. This value may be somewhat imprecise if you are using estimated line heights, but it should be good enough. In this example, I gave the table a view of the height constraint (as well as the width and center Y) and made an IBOutlet for it (heightCon). The only code needed was,

@interface RDTableView ()
@property (weak,nonatomic) IBOutlet NSLayoutConstraint *heightCon;
@end

@implementation RDTableView

-(void)reloadData {
    [super reloadData];
    self.heightCon.constant = MIN(200, self.contentSize.height);
}

      



You will also have to override reloadRowsAtIndexPaths: withRowAnimation: and reloadSections: withRowAnimation: if you update the table with either of them.

+3


source


When you (re) upload data to yours TableView

, you can do this. TableView

will only occupy the desired height



CGRect frame = youTableView;
frame.size.height = CELL_HEIGHT*[yourArray count];
if(frame.size.height > MAX_TABLEVIEW_HEIGHT)
{
    frame.size.height = MAX_TABLEVIEW_HEIGHT
}
youTableView.frame = frame;

      

0


source


This is similar to the chicken / egg problem you run into when designing your UI. It looks like you want to set the height of the floating table view based on how many rows it contains * height for each row, but the tableview doesn't know any of that data until it is drawn, that is, [tableView reloadData] and the corresponding height for delegate methods are called strings.

I suggest rendering the tableview off-screen somewhere, draw all the rows, sum all the heights for each row, and then present the view to the user with the appropriate CGRect.

0


source







All Articles