Created
March 19, 2020 18:56
-
-
Save KaQuMiQ/3d7500e6299ba7d4eb9d73137c62f8c8 to your computer and use it in GitHub Desktop.
Autoresizing text view
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
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