Created
January 3, 2021 03:46
-
-
Save yosshi4486/4494f7de352251a19cf3d8da8f447c05 to your computer and use it in GitHub Desktop.
UITextView on UITableViewCellの実装例
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
func textViewDidChange(_ textView: UITextView) { | |
// https://www.damienpontifex.com/posts/self-sizing-uitableviewcell-with-uitextview-in-ios8/ | |
// UITextView on UITableViewCellの良い解説記事 | |
let size = textView.bounds.size | |
let newSize = textView.sizeThatFits(CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude)) | |
// 上記のheightを直接比較すると0.5ptぐらい誤差が出てうまく処理を弾けないことがあるので | |
// 判定範囲を広げた | |
let difference = abs(newSize.height - size.height) | |
let textLineHeight = textView.font?.lineHeight ?? 0 | |
let shoudUpdateCellHeight = difference >= textLineHeight | |
if shoudUpdateCellHeight { | |
UIView.performWithoutAnimation { | |
tableView.beginUpdates() | |
tableView.endUpdates() | |
if let indexPathForSelectedRow = tableView.indexPathForSelectedRow { | |
tableView.scrollToRow(at: indexPathForSelectedRow, at: .bottom, animated: false) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment