21

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
  }

}
Ekta Padaliya
  • 5,743
  • 3
  • 39
  • 51
WKL
  • 504
  • 1
  • 5
  • 17
  • did you tried self.items.count*row_height this will give the height based on content but u need to write other conditions to check the screen height too – Smile Dec 23 '15 at 06:03
  • Why don't you add the top and bottom imageViews in the header and footer of tableview? – Muneeba Dec 23 '15 at 06:17
  • Headers and footers does not really work because the top and bottom imageView is just a representative of views. In actual, it is a view with much more components, label, images and constraints. – WKL Dec 23 '15 at 06:43
  • The try adding constraints to the bottom view from the bottom and top view from top layout guide and their heights fixed and the table view constraints to their respective neighbors i.e. top and bottom. – Arpit Dhamane Dec 23 '15 at 06:56
  • Do you mean that the top and bottom images are static on the _view_? because if they were static on the _screen_ then the `tableView` would have to be always the same. – rr1g0 Dec 23 '15 at 07:16

14 Answers14

32
  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.

Cody
  • 650
  • 9
  • 16
  • 1
    awesome! I really can't believe this is not part of iOS. Isn't this a really common use case? – Martin Massera Apr 28 '17 at 20:05
  • thanks @MartinMassera! I agree, it took me awhile to figure out how to best do this, but I've used this approach several times now. I didn't want to subclass, but I thought it was still the cleanest rather than updating constraints manually. – Cody Apr 28 '17 at 23:34
  • awesome! best solution – Bob May 22 '17 at 15:47
19

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
    }
}
nikans
  • 2,468
  • 1
  • 28
  • 35
  • Thanks for the help but i want to one constrint on this.. if tableview size greater then safe area size then i want to enable scrolling and this effect stop. is it possible? – Maulik shah May 29 '20 at 08:53
10

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()
        }
    }
}
Joshua Hart
  • 772
  • 1
  • 21
  • 31
8

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.

rr1g0
  • 383
  • 4
  • 13
8

Update Swift 4 this code working be good

self.scrollView.layoutIfNeeded()
self.view.layoutIfNeeded()
self.tableViewHeightConstraint.constant = CGFloat(self.tableView.contentSize.height)
Puji Wahono
  • 338
  • 5
  • 10
4

Update for Swift 5. Adding maxHeight so that you can specify how tall you want your tableView to be

class SelfSizingTableView: UITableView {
    var maxHeight = CGFloat.infinity

    override var contentSize: CGSize {
        didSet {
            invalidateIntrinsicContentSize()
            setNeedsLayout()
        }
    }

    override var intrinsicContentSize: CGSize {
        let height = min(maxHeight, contentSize.height)
        return CGSize(width: contentSize.width, height: height)
    }
}
Linh Ta
  • 593
  • 6
  • 11
  • https://i.stack.imgur.com/YcdkR.png .... how can i do this..Thanks for the help but i want to one constrint on this.. if tableview size greater then safe area size then i want to enable scrolling and this effect stop. is it possible? – Maulik shah May 29 '20 at 09:17
  • @Maulikshah you can try getting the `view` height minus `safe area` height and set that to the `tableView` maxHeight. The `tableView` will become scrollable when it reaches its maxHeight. – Linh Ta Jun 24 '20 at 07:10
3

You probably have to implement the table view intrinsic content size. Please check this answer to see if it helps.

I remember having this problem and even created a custom UITableView subclass.

#import "IntrinsicTableView.h"

@implementation IntrinsicTableView

#pragma mark - UIView

- (CGSize)intrinsicContentSize
{
    return CGSizeMake(UIViewNoIntrinsicMetric, self.contentSize.height);
}

#pragma mark - UITableView

- (void)endUpdates
{
    [super endUpdates];
    [self invalidateIntrinsicContentSize];
}

- (void)reloadData
{
    [super reloadData];
    [self invalidateIntrinsicContentSize];
}

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
{
    [super reloadRowsAtIndexPaths:indexPaths withRowAnimation:animation];
    [self invalidateIntrinsicContentSize];
}

- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation
{
    [super reloadSections:sections withRowAnimation:animation];
    [self invalidateIntrinsicContentSize];
}

- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
{
    [super insertRowsAtIndexPaths:indexPaths withRowAnimation:animation];
    [self invalidateIntrinsicContentSize];
}

- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation
{
    [super insertSections:sections withRowAnimation:animation];
    [self invalidateIntrinsicContentSize];
}

- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
{
    [super deleteRowsAtIndexPaths:indexPaths withRowAnimation:animation];
    [self invalidateIntrinsicContentSize];
}

- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation
{
    [super deleteSections:sections withRowAnimation:animation];
    [self invalidateIntrinsicContentSize];
}

@end
Community
  • 1
  • 1
Raphael Oliveira
  • 7,751
  • 5
  • 47
  • 55
2

In that case, don't make your bottom cell static, make it a part of table view and insert this bottom image in last row using table view delegate method - insertRowAtIndexPath

Vikas Mishra
  • 246
  • 1
  • 12
2

In this type of case add your bottom imageView(red) in a table footer view.

To add footer view in UITableView you can use:

tableViewObj.tableFooterView = footerViewObj;
Mehul Sojitra
  • 1,181
  • 9
  • 15
2

Try this also

in ViewDidLoad

 self.table.estimatedRowHeight = 44.0 ;
self.table.rowHeight = UITableViewAutomaticDimension;

Height for row at index path

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;}
Kishore Kumar
  • 4,265
  • 3
  • 26
  • 47
2

Easy way here.

Step 1: Set a height constraint for the table view

Step 2: Control drag the constraint

Step 3: Before you return the count of the rows. In numberOfRowsInSection method, do

tableViewHeightConstraint.constant = tableView.rowHeight * CGFloat(someArray.count)

Of course you can edit the height anchor programmatically, the logic here is to adjust the table view height according to the cell height and cell number.

0

Based on solution @nikans, written in Xamarin

[Register(nameof(DynamicSizeTableView)), DesignTimeVisible(true)]
public class DynamicSizeTableView : UITableView
{
    public override void LayoutSubviews()
    {
        base.LayoutSubviews();
        if (Bounds.Size != IntrinsicContentSize)
            InvalidateIntrinsicContentSize();
    }

    public override CGSize IntrinsicContentSize => ContentSize;

    public DynamicSizeTableView(CGRect frame) : base(frame) { }

    public DynamicSizeTableView(IntPtr handle) : base(handle) { }
}
Maury
  • 604
  • 2
  • 8
  • 25
0

Here is the simplest Solution

  • First Give a height to the tableView.

  • Create outlet of that height in view Controller. let's say tableViewHeight

  • Then do this in viewDidLoad or where you populate the data after calling tableView.reloadData()

      var height = 0.0
      for i in 0..<items.count {
          let frame = tableView.rectForRow(at: IndexPath(row: i, section: 0))
          height += frame.size.height
      }
    
      tableViewHeight.constant = height
    

This Also Works with tableViews that have dynamic cell heights

Aarfeen Ahmad
  • 76
  • 1
  • 8
-2

Based on solution of @rr1g0

Updated for Swift 5 in 2020, and works with TableViews with sections too.

Create height constraint for tableView and create an outlet to it. And in viewDidLayoutSubviews() use the code below:

var tableViewHeight: CGFloat = 0

for section in 0..<tableView.numberOfSections {
    for row in 0..<tableView.numberOfRows(inSection: section) {
        tableViewHeight += tableView(tableView, heightForRowAt: IndexPath(row: row, section: section))
    }
}

tableViewHeightConstraint.constant = tableViewHeight
banderson
  • 65
  • 1
  • 11