uadnal
uadnal

Reputation: 11435

Dynamically set UIScrollView height and UITableView Height depending on content

Setup: I have a scrollview with a label, uiimage, and a tableview (grouped) nested within. The label, uiimage, and tableveiw are populated by a webservice. The last section in the grouped table view contains text that will never be the same and could be as long as 5 characters to 250+. Also, this view is pushed from a basic tableview (so it has a navigation bar. If that matters at all).

Expected: The tableview should extend in height depending on the length of the content received from the web service. Then set the scrollview height to accommodate the height of the tableview

Problem: I'm not quite sure how to approach the issue. I really only know how to change the height to fixed values, which will not work properly in many scenarios.

Upvotes: 1

Views: 2388

Answers (2)

tc.
tc.

Reputation: 33592

The width and height of the cell are ignored; the cell cell is re-sized according to the value you return from -tableView:heightForRowAtIndexPath: or (failing that) tableView.rowHeight. It might appear as if the cell is big enough if the label in the cell is sized to be big enough, because the label is allowed to be bigger than (and render outside) the cell.

One way is to override -tableView:heightForRowAtIndexPath: to return the correct height. This isn't really the intended use of UITableView (it's primarily designed for lots of rows of a single height, dynamically generated from a list of content).

Another way is to set tableView.tableFooterView = myCustomFooter instead. This is probably the easiest way. Size it correctly before performing the assignment (the height matters; the table view will set the width for you anyway). Also make sure that the autoresizing flags are not set, or the size will appear to randomly change when the table view changes size (e.g. on autorotation).

Upvotes: 1

NWCoder
NWCoder

Reputation: 5266

I'd just focus on the variable height element, figure out the height that fits the text there. To figure out the height that a string will take when rendered use a snippet like this:

CGFloat MY_TABLECELL_WIDTH = 320;
CGFloat MY_MAX_HEIGHT = 10000;
UIFont *MY_FONT = nil; // load the correct font here.
CGSize maxSize = CGSizeMake(MY_TABLECELL_WIDTH,MY_MAX_HEIGHT);
CGSize textSize = [serverString sizeWithFont:MY_FONT 
                        constrainedToSize:maxSize 
                        lineBreakMode:UILineBreakModeWordWrap]; 

Upvotes: 0

Related Questions