0

Context:

I have a pop up view that contains a tableview. I would like the pop up view to be less than the whole height of the screen but would like the tableview to scale with the number of rows it has. (If the table view contains 2 rows then it would fit those 2 rows and would not scroll, if the table view has 30 rows it will max out at the height of the screen and allow scrolling).

View Hierarchy:



    - viewContainer (clear background, whole view)
    -- viewPopUp (pop up container)
    --- labelHeader
    --- tableView
    --- buttonOK


Constraints:



    viewPopUp.centerY = viewContainer.centerY
    viewPopUp.centerX = viewContainer.centerX
    viewPopUp.leadingSpaceTo superView = 32 @750
    viewPopUp.trailingSpaceTo superView = 32 @750
    viewPopUp.width &lt= 300
    viewPopUp.height &lt= 0.8 * viewContainer.height

    labelHeader.topSpaceTo superView = 0
    labelHeader.leadingSpaceTo superView = 0
    labelHeader.trailingSpaceTo superView = 0
    labelHeader.bottomSpaceTo tableView = 0
    labelHeader.height = 33

    tableView.topSpaceTo labelHeader = 0
    tableView.leadingSpaceTo superView = 0
    tableView.trailingSpaceTo superView = 0
    tableView.bottomSpaceTo buttonOk = 0
    tableView.height &gt= 0
    tableView.height = 0 @200

    buttonOk.topSpaceTo tableView = 0
    buttonOK.leadingSpaceTo superView = 0
    buttonOK.trailingSpaceTo superView = 0
    buttonOk.bottomSpaceTo superview = 0
    buttonOK.height = 35


My Question:

In my UIViewController's viewDidLoad I know exactly how many rows will need to be represented in this tableView and I would like to add an additional constraint to have the tableView scale to this number as described in the context above.

I have tried tableView.height = count * rowHeight @500 but this does not update the view. I am not sure if I am not calling something like needsUpdateConstraints or needsUpdateLayout etc.

If I add the above constraint as required then it will update the tableView as expected but I receive constraint warnings and I believe this will break if it pushes the tableView past the size of the screen which is why I wanted to add it as a non-required constraint so it will drop off after it reaches the screen height.

Does anyone have any ideas on how I can reach this desired outcome?

Thanks!

egarlock
  • 559
  • 3
  • 11

1 Answers1

0

Assuming that the height of the rows are always the same, you could calculate the height of the table, check it against the view height and set this value to a referenced height constraint added to the table view. The code would look something like:

//calculate the height
var tableHeight = numberOfRows * rowHeight
if tableheight > maxHeight {
tableHeight = maxHeight
}
self.tableHeightConstraint.constant = tableHeight //this constraint should be a iboutlet
self.view.layoutIfNeeded()

Hope it helps.

Lucho
  • 1,024
  • 1
  • 15
  • 24