Last active
June 9, 2019 17:36
-
-
Save rnystrom/cde11d9fc85e15632bd97f72f8c203cc to your computer and use it in GitHub Desktop.
Self-sizing UITableViewCell with an h-scrolling UITextView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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