Created
January 16, 2020 08:40
-
-
Save egzonpllana/154703a9dc8ecbbea2706c0782e093b3 to your computer and use it in GitHub Desktop.
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
// Improved and update **Luke Chase's** [answer][1] to Swift 5, XCode 11, iOS 13 to get text view number of lines and autoresize table view cell height. | |
// 1) You can use storyboard with static cell height to design it as you want. | |
// 2) In viewDidLoad add your estimated row height and your textView delegate. | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
quoteTextView.delegate = self | |
tableView.estimatedRowHeight = 142 | |
} | |
// 3) Add table view delegates for heightForRowAt: | |
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { | |
return UITableView.automaticDimension | |
} | |
// 4) Conform to UITextViewDelegate to listen when user inputs text. | |
extension ViewController: UITextViewDelegate { | |
func textViewDidChange(_ textView: UITextView) { | |
// Refresh tableView cell | |
if textView.numberOfLines > 2 { // textView in storyboard has two lines, so we match the design | |
// Animated height update | |
DispatchQueue.main.async { | |
self.tableView?.beginUpdates() | |
self.tableView?.endUpdates() | |
} | |
} | |
} | |
} | |
// 5) Add UITextView extension so you avoid redundant code and use all over the app. | |
extension UITextView { | |
var numberOfLines: Int { | |
// Get number of lines | |
let numberOfGlyphs = self.layoutManager.numberOfGlyphs | |
var index = 0, numberOfLines = 0 | |
var lineRange = NSRange(location: NSNotFound, length: 0) | |
while index < numberOfGlyphs { | |
self.layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange) | |
index = NSMaxRange(lineRange) | |
numberOfLines += 1 | |
} | |
return numberOfLines | |
} | |
} | |
**Preview** | |
[![autoresize textview height swift][2]][2] | |
[1]: https://stackoverflow.com/a/39309641/7987502 | |
[2]: https://i.stack.imgur.com/X7J7s.gif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment