Last active
February 9, 2022 06:11
-
-
Save raygun101/3da0382f798e8f1d0b68fea66a6f539d to your computer and use it in GitHub Desktop.
π° Layered Cakewalk [Swift] - Auto sizing UITextView where intrinsicContentSize reflects the text size.
This file contains hidden or 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
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