Search code examples
iosuitableviewautolayoutnslayoutconstraint

How to create a table whose height can be autoadjusted


I have a tableview whose height is 70% of the screen sometimes I don't have enough rows to fill up all 70% then in that case there are some empty spaces with blank rows and it looks awkward.so if the height gets auto adjusted to the tablerows content then it'd be great but I couldn't find anything related to do this.

so how to do it ?


Solution

  • You can do like below

    • Take IBOutlet of height constraints of UITableView

    And you will be find height of tableView based on your data/rows

    tableView.contentSize.height
    

    Now You need to change your height constraints based below condition

    if  tableView.contentSize.height < UIScreen.main.bounds.size.height { // Instead of UIScreen.main.bounds.size.height, change as per your requirment
    
      yourTblHeightConstraints.constant = tableView.contentSize.height
      self.view.layoutIfNeeded()
    }
    else {
      yourTblHeightConstraints.constant = UIScreen.main.bounds.size.height // Instead of UIScreen.main.bounds.size.height, change here as you need
      self.view.layoutIfNeeded()
    }