Skip to content

Instantly share code, notes, and snippets.

@benjaminbojko
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjaminbojko/86e7d6e155f09569acc1 to your computer and use it in GitHub Desktop.
Save benjaminbojko/86e7d6e155f09569acc1 to your computer and use it in GitHub Desktop.
Calculate content size for UITextView
//
// UITextView+LayoutHelpers.h
//
// Created by Benjamin Bojko on 10/24/14.
// Copyright (c) 2014 Benjamin Bojko. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UITextView (LayoutHelpers)
/**
* Returns the calculated size of its text contents by adding extra padding for content- and text-container-insets as well as text-container line-fragment-padding.
*/
- (CGSize)calculatedContentSize;
@end
//
// UITextView+LayoutHelpers.m
//
// Created by Benjamin Bojko on 10/24/14.
// Copyright (c) 2014 Benjamin Bojko. All rights reserved.
//
#import "UITextView+LayoutHelpers.h"
@implementation UITextView (LayoutHelpers)
- (CGSize)calculatedContentSize {
CGSize contentSize = self.bounds.size;
UIEdgeInsets contentInsets = self.contentInset;
UIEdgeInsets contentainerInsets = self.textContainerInset;
float maxWidth = contentSize.width;
maxWidth -= 2.0f * self.textContainer.lineFragmentPadding;
maxWidth -= contentInsets.left + contentInsets.right + contentainerInsets.left + contentainerInsets.right;
// Fix for font not being defined if the text view is not selectable in iOS 7
BOOL selectable = self.selectable;
self.selectable = YES;
CGSize textSize = [self.attributedText boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
self.selectable = selectable;
contentSize.height = ceilf(textSize.height);
contentSize.height += contentInsets.top + contentInsets.bottom + contentainerInsets.top + contentainerInsets.bottom;
return contentSize;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment