0

I'm creating an iOS app which contains quite complicated scroll view (view, table, view, image, and so on), and I'm curious: may I create a self-sizing table using Auto Layout?.

What I want: if the table contains three rows, then table's height is equal to these three rows, but if there are 50 rows in the table, then table's height does not exceed ten rows.

I looked on constraint "height is equal or less than XXX", but it is obviously doesn't work.

Yar Geel
  • 31
  • 1
  • 4
  • You should change table height on willDisplayCell. Check the indexpath to see if it more than the 9th then stop incrementing the table height – Maz Oct 01 '18 at 14:00
  • You can do dynamically for every elements. If the cell size is static , you can control if tableview elements > 10 , return 10*cellsize – Ali Ihsan URAL Oct 01 '18 at 14:01

1 Answers1

1

I explained how to do this years ago in this answer. That answer is in Objective-C. It is simple to translate the code to Swift, but I'll do it for you:

Make a subclass of UITableView. In your subclass, override intrinsicContentSize:

class MyTableView: UITableView {
    override var intrinsicContentSize: CGSize {
        layoutIfNeeded()
        return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
    }
}

If you modify the number of rows in the table view after initially setting it up, you should tell the table view to invalidateIntrinsicContentSize() after doing so, for example after you call reloadData(), endUpdates(), etc. Or you could override those methods in MyTableView to also call invalidateIntrinsicContentSize() automatically.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • thanks all for answers, I solved an issue by the similar way: counting rows and set table height programmatically. actually I've asked about possibility to set dynamic height by AutoLayout only - ok, looks like it's impossible :| – Yar Geel Oct 02 '18 at 03:31