Last active
August 29, 2015 14:08
-
-
Save benjaminbojko/86e7d6e155f09569acc1 to your computer and use it in GitHub Desktop.
Calculate content size for UITextView
This file contains hidden or 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
// | |
// 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 |
This file contains hidden or 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
// | |
// 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