Skip to content

Instantly share code, notes, and snippets.

@phlippieb
Created January 25, 2017 05:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phlippieb/7524270cad67dcb8edeea0769630e491 to your computer and use it in GitHub Desktop.
Save phlippieb/7524270cad67dcb8edeea0769630e491 to your computer and use it in GitHub Desktop.
`MaxHeightTextView` overrides `UITextView`'s `intrinsicContentSize` and `layoutSubviews` to allow it to grow to fit its content size, but only up to a specified max height. Once the text view reaches this max height, its content will start to scroll. Use with AutoLayout. Specifically, set up a fixed width, and two height constraints with greater…
//
// File.swift
// Kalido
//
// Created by Phlippie Bosman on 2016/11/17.
// Copyright © 2016 Kalido. All rights reserved.
//
class MaxHeightTextView: UITextView {
open var maxHeight: CGFloat?
open var fixedTextViewWidth: CGFloat?
private var calculatedContentSize: CGSize {
var width: CGFloat = fixedTextViewWidth ?? bounds.size.width
width += ((textContainerInset.left + textContainerInset.right) / 2)
let comfySize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
return sizeThatFits(comfySize)
}
override var intrinsicContentSize: CGSize {
var size = self.calculatedContentSize
size.width += (textContainerInset.left + textContainerInset.right) / 2.0
size.height += (textContainerInset.top + textContainerInset.bottom) / 2.0
if let max = maxHeight {
size.height = min(size.height, max)
}
return size
}
override func layoutSubviews() {
super.layoutSubviews()
if !self.bounds.size.equalTo(intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
}
@JoaoFloresDev
Copy link

thank you so much!

@worldbridgerstudios
Copy link

Thank you! I've been trying solutions for hours, this is the first implementation that works.

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