Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic UITableView height

I would like to set the UITableView to match the height for all the contents in the table view.

This is my storyboard

enter image description here

The problem with this is the top and bottom ImageView is always static on the screen.

enter image description here

The there are suppose to be 10 items on the table view but only 7 shows up due to screen size limitation. I would like to show all 10 before user is able to see the bottom ImageView. (btw, all 3 of the views ie. both the image views and tableview is in a uiscrollview)

IDEAL

enter image description here

Some of the other limitations that i have to work with is that the number of items in the table view is dynamic meaning it can be in any amount of usually less than 10 that i will later retrieve from an api. And the cell height is also dynamic depending on the contents.

I have only just started with some simple code

class ExampleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
      @IBOutlet weak var tableView: UITableView!

  var items: [String] = [
    "Item 01", "Item 02", "Item 03", "Item 04", "Item 05",
    "Item 06", "Item 07", "Item 08", "Item 09", "Item 10"]

  override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.items.count;
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
    cell.textLabel?.text = self.items[indexPath.row]
    return cell
  }

}
like image 731
WKL Avatar asked Dec 23 '15 06:12

WKL


5 Answers

  1. Subclass your UITableView to override the intrinsicContentSize to be its contentSize, like this:

    override var intrinsicContentSize: CGSize {
        return contentSize
    }
    
  2. Then use automatic row heights for your table, so your exampleViewController's viewDidLoad would have:

    tableView.estimatedRowHeight = 44
    

    And the UITableViewDelegate function:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
  3. When you receive data from your API and reload your table, just call:

    tableView.invalidateIntrinsicContentSize()
    

    This will tell your table to resize itself to the same size as its contents (because of the override), and move your bottom image as needed.


If your storyboard throws an error saying that your UIScrollView has an ambiguous height because there's no height constraint on the UITableView, select your UITableView and give it a placeholder intrinsic size in the Size Inspector.

like image 114
Cody Avatar answered Nov 10 '22 09:11

Cody


The answers using the subclassing technique are incomplete. You should also override layoutSubviews() like this.

public class DynamicSizeTableView: UITableView
{
    override public func layoutSubviews() {
        super.layoutSubviews()
        if bounds.size != intrinsicContentSize {
            invalidateIntrinsicContentSize()
        }
    }

    override public var intrinsicContentSize: CGSize {
        return contentSize
    }
}
like image 30
nikans Avatar answered Nov 10 '22 09:11

nikans


You need to set an IBOutlet to the NSLayoutConstraint that sets the tableView height (first you need create the height constraint with any value, doesn't matter) and then ctrl drag it to your class file

enter image description here

Then in your viewWillAppear you have to calculate the tableView height and set it. Like this:

var tableViewHeight:CGFloat = 0;
for (var i = tableView(self.tableView , numberOfRowsInSection: 0) - 1; i>0; i-=1 ){
    tableViewHeight = height + tableView(self.tableView, heightForRowAtIndexPath: NSIndexPath(forRow: i, inSection: 0) )
}
tableViewHeightLayout.constant = tableViewHeight

And that's pretty much it. That will give your scrollView content size and shouldn't raise any warnings.

like image 21
rr1g0 Avatar answered Nov 10 '22 09:11

rr1g0


Update Swift 4 this code working be good

self.scrollView.layoutIfNeeded()
self.view.layoutIfNeeded()
self.tableViewHeightConstraint.constant = CGFloat(self.tableView.contentSize.height)
like image 8
Puji Wahono Avatar answered Nov 10 '22 09:11

Puji Wahono


This is what I utilize in production apps:

Swift 5, 2021

import UIKit

class DynamicTableView: UITableView {

    /// Will assign automatic dimension to the rowHeight variable
    /// Will asign the value of this variable to estimated row height.
    var dynamicRowHeight: CGFloat = UITableView.automaticDimension {
        didSet {
            rowHeight = UITableView.automaticDimension
            estimatedRowHeight = dynamicRowHeight
        }
    }

    public override var intrinsicContentSize: CGSize { contentSize }

    public override func layoutSubviews() {
        super.layoutSubviews()
        if !bounds.size.equalTo(intrinsicContentSize) {
            invalidateIntrinsicContentSize()
        }
    }
}
like image 7
Joshua Hart Avatar answered Nov 10 '22 09:11

Joshua Hart