简体   繁体   中英

Automatic height of UITableView based on its content

I have a UITableView within a standard ViewController and I'd like its height to stretch along with its contents - exactly like a normal webpage. So for example, if a single row is 50px and two rows exist, then the height would go no further than those two rows (100). However, if there are 100 rows then the tableview should go beyond the bottom of the window.

I'd also like to keep a margin of 10 between the bottom of the table view and the window when the tableview is taller that the main window itself and the user has scrolled to the bottom of the list.

Is there a way in interface builder to do this or is this something that has to be done in code?

Here's an example of what I want it to look like when there are three items in the list;

在此处输入图片说明

And when it reaches the bottom of the list, it has a constraint in relation to the bottom of the window;

在此处输入图片说明

I think what you want is easier to get if you just expand the table to the bottom of the view (with your 10px margin) and make the background transparent/grey. Then, configure each row to have a white background. The result will look as your screenshot.

Is there any specific reason to expand the table frame? if so, please explain...

I am also doing same thing what you want to after searching on stack overflow found solution.

If you want to set the table view height dynamically, I think the best way is to set the table view height constraint equal to its content size after the table view done loading. I mean something like,

tableViewHeightConstraint.constant = tableView.contentSize.height

Just do this -

  • Add UITableView in UIScrollview. This will give infinite scroll to tableview.
  • Disable UITableView scroll.

  • Add a height constraint for table view. (height = 50px)

  • Select table height constraint and Set priority to High (750) 在此处输入图片说明

  • Create an outlet of the height constraint(Ctrl+Drag). 在此处输入图片说明

  • Set the height constraint to table view content height.

  • Add below code in cellForRowAt :

tableViewHeightConstraint.constant = tableview.contentSize.height

wherever you need to reload data of your table.

Hope this would help other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM