Skip to content

Instantly share code, notes, and snippets.

@rnystrom
Last active June 9, 2019 17:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnystrom/cde11d9fc85e15632bd97f72f8c203cc to your computer and use it in GitHub Desktop.
Save rnystrom/cde11d9fc85e15632bd97f72f8c203cc to your computer and use it in GitHub Desktop.
Self-sizing UITableViewCell with an h-scrolling UITextView
class Cell: UITableViewCell {
let textView = UITextView()
let scrollView = UIScrollView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.alwaysBounceHorizontal = true
scrollView.scrollsToTop = false
scrollView.alwaysBounceVertical = false
contentView.addSubview(scrollView)
textView.isEditable = false
textView.translatesAutoresizingMaskIntoConstraints = false
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.isScrollEnabled = false
textView.scrollsToTop = false
scrollView.addSubview(textView)
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: contentView.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
scrollView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
textView.topAnchor.constraint(equalTo: scrollView.topAnchor),
textView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
textView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
textView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
// this is the "trick"
scrollView.heightAnchor.constraint(equalTo: textView.heightAnchor)
])
}
override func layoutMarginsDidChange() {
super.layoutMarginsDidChange()
textView.contentInset = layoutMargins
}
override func prepareForReuse() {
super.prepareForReuse()
scrollView.contentOffset = .zero
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment