Skip to content

Instantly share code, notes, and snippets.

@ElyDantas
Last active February 14, 2019 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElyDantas/b597c275b4674430e62c02e2a9e4d457 to your computer and use it in GitHub Desktop.
Save ElyDantas/b597c275b4674430e62c02e2a9e4d457 to your computer and use it in GitHub Desktop.
Resizing UITableView to fit Content Swift
StackOverflow answer by fl034 user.
Link: https://stackoverflow.com/questions/2595118/resizing-uitableview-to-fit-content/48623673#48623673
Swift 4.2 solution without KVO, DispatchQueue, or setting constraints yourself.
This solution is based on Gulz's answer.
1) Create a subclass of UITableView:
import UIKit
final class ContentSizedTableView: UITableView {
override var contentSize:CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
}
2) Add a UITableView to your layout and set constraints on all sides. Set the class of it to ContentSizedTableView.
3) You should see some errors, because Storyboard doesn't take our subclass' intrinsicContentSize into account.
Fix this by opening the size inspector and overriding the intrinsicContentSize to a placeholder value.
This is an override for design time. At runtime it will use the override in our ContentSizedTableView class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment