简体   繁体   中英

iOS AutoLayout self-sizing whole table (not cells!) height

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM