Skip to content

Instantly share code, notes, and snippets.

@KaQuMiQ
Created March 19, 2020 18:56
Show Gist options
  • Save KaQuMiQ/3d7500e6299ba7d4eb9d73137c62f8c8 to your computer and use it in GitHub Desktop.
Save KaQuMiQ/3d7500e6299ba7d4eb9d73137c62f8c8 to your computer and use it in GitHub Desktop.
Autoresizing text view
import UIKit
public final class TextView: UITextView {
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
layoutManager.delegate = self
isScrollEnabled = false
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError() }
public override var intrinsicContentSize: CGSize {
sizeThatFits(CGSize(width: bounds.width, height: .greatestFiniteMagnitude))
}
public var numberOfLines: Int {
var linesCount: Int = 0
var idx: Int = 0
let lineRange: NSRangePointer = .allocate(capacity: 1)
while idx < layoutManager.numberOfGlyphs {
layoutManager.lineFragmentRect(forGlyphAt: idx, effectiveRange: lineRange)
idx = NSMaxRange(lineRange.pointee)
linesCount += 1
}
lineRange.deallocate()
return linesCount
}
}
extension TextView: NSLayoutManagerDelegate {
public func layoutManagerDidInvalidateLayout(_ sender: NSLayoutManager) {
invalidateIntrinsicContentSize()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment