Skip to content

Instantly share code, notes, and snippets.

@aataraxiaa
Last active September 22, 2023 16:35
Show Gist options
  • Save aataraxiaa/81d4588cfd850b9c1316628993c1f3d3 to your computer and use it in GitHub Desktop.
Save aataraxiaa/81d4588cfd850b9c1316628993c1f3d3 to your computer and use it in GitHub Desktop.
UITextView extension with method to calculate new height based on content
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
}
}
@MohamedElabdEmber
Copy link

Thanks a lot for this extension, you really made my day 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment