Skip to content

Instantly share code, notes, and snippets.

@raygun101
Last active February 9, 2022 06:11
Show Gist options
  • Save raygun101/3da0382f798e8f1d0b68fea66a6f539d to your computer and use it in GitHub Desktop.
Save raygun101/3da0382f798e8f1d0b68fea66a6f539d to your computer and use it in GitHub Desktop.
🍰 Layered Cakewalk [Swift] - Auto sizing UITextView where intrinsicContentSize reflects the text size.
import UIKit
///
/// 🍰 Layered Cakewalk - UITextViewWithAutoLayout
///
/// A UITextView that has an `intrinsicContentSize` equal to the content size.
///
class UITextViewWithAutoLayout : UITextView
{
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
private var _observer: NSObjectProtocol?
///
override init(frame: CGRect, textContainer: NSTextContainer?)
{
super.init(frame: frame, textContainer: textContainer)
self.enablesReturnKeyAutomatically = true
self.backgroundColor = .clear
self.layoutMargins = .zero
self.insetsLayoutMarginsFromSafeArea = false
self.contentInset = .zero
self.textContainerInset = .zero
self.textContainer.lineFragmentPadding = 0
_observer = self.observe(\.contentSize, options: [.old, .new])
{
view, change in
if change.oldValue != change.newValue
{
view.invalidateIntrinsicContentSize()
}
}
}
override var intrinsicContentSize: CGSize
{
self.contentSize
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment