Last active
September 22, 2023 16:35
-
-
Save aataraxiaa/81d4588cfd850b9c1316628993c1f3d3 to your computer and use it in GitHub Desktop.
UITextView extension with method to calculate new height based on content
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
extension UITextView { | |
/** | |
Calculates if new textview height (based on content) is larger than a base height | |
- parameter baseHeight: The base or minimum height | |
- returns: The new height | |
*/ | |
func newHeight(withBaseHeight baseHeight: CGFloat) -> CGFloat { | |
// Calculate the required size of the textview | |
let fixedWidth = frame.size.width | |
let newSize = sizeThatFits(CGSize(width: fixedWidth, height: .greatestFiniteMagnitude)) | |
var newFrame = frame | |
// Height is always >= the base height, so calculate the possible new height | |
let height: CGFloat = newSize.height > baseHeight ? newSize.height : baseHeight | |
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: height) | |
return newFrame.height | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for this extension, you really made my day 🙏