Created
January 25, 2017 05:35
-
-
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…
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
// | |
// 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() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! I've been trying solutions for hours, this is the first implementation that works.