iOS7 UITextView contentsize.height alternative
With this following code, you can change the height of your UITextView depending of a fixed width (it's working on iOS 7 and previous version) :
- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
UITextView *textView = [[UITextView alloc] init];
[textView setAttributedText:text];
CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
return size.height;
}
With this function, you will take a NSAttributedString and a fixed width to return the height needed.
If you want to calculate the frame from a text with a specific font you, need to use the following code :
- (CGSize)text:(NSString *)text sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
CGRect frame = [text boundingRectWithSize:size
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName:font}
context:nil];
return frame.size;
}
else
{
return [text sizeWithFont:font constrainedToSize:size];
}
}
You can add that SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO
on your prefix.pch file in your project as:
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
You can also replace the previous test SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)
by :
if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)])
UITextView content size different in iOS7
The content size property no longer works as it did on iOS 6. Using sizeToFit as others suggest may or may not work depending on a number of factors.
It didn't work for me, so I use this instead:
- (CGFloat)measureHeightOfUITextView:(UITextView *)textView
{
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
{
// This is the code for iOS 7. contentSize no longer returns the correct value, so
// we have to calculate it.
//
// This is partly borrowed from HPGrowingTextView, but I've replaced the
// magic fudge factors with the calculated values (having worked out where
// they came from)
CGRect frame = textView.bounds;
// Take account of the padding added around the text.
UIEdgeInsets textContainerInsets = textView.textContainerInset;
UIEdgeInsets contentInsets = textView.contentInset;
CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
frame.size.width -= leftRightPadding;
frame.size.height -= topBottomPadding;
NSString *textToMeasure = textView.text;
if ([textToMeasure hasSuffix:@"\n"])
{
textToMeasure = [NSString stringWithFormat:@"%@-", textView.text];
}
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
NSDictionary *attributes = @{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };
CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
return measuredHeight;
}
else
{
return textView.contentSize.height;
}
}
How do I size a UITextView to its content on iOS 7?
I favor this minimal code change: Just add these two lines after addSubview
and before grabbing the height
of the frame
...
[scrollView1 addSubview: myTextView];
[myTextView sizeToFit]; //added
[myTextView layoutIfNeeded]; //added
CGRect frame = myTextView.frame;
...
This is tested backwards compatible with iOS 6. NOTE that it shrink-wraps the width. If you're just interested in the height and have a fixed width, just grab the new height but set the original width, and it works just as before on both iOS 6 and 7.
(Speculation: it does size to fit on iOS 7 as well, but the layout is updated later or in a separate thread, and that this forces the layout immediately so that its frame is updated in time for using its height value a few lines later in the same thread.)
NOTES:
1) You might or might not have implemented the outer container resize this way. It does seem to be a common snippet, though, and I've used it in my projects.
2) Since sizeToFit
seems to work as expected on iOS 7, you likely don't need the premature addSubView. Whether it will still work on iOS 6 then is untested by me.
3) Speculation: The extra layoutIfNeeded
mid-thread might be costly. The alternative as I see it is to resize the outer container on the layout callback (fired or not depending on if the OS decides whether layout is needed or not) where the outer container resize will cause another layout update. Both updates might be combined with other layout updates to be more efficient. If you do have such a solution and you can show that it is more efficient, add it as answer and I'll be sure to mention it here.
IOS7 get UITextView contentSize before viewDidAppear method is called?
You can call [self.textView layoutIfNeeded]
after creating it with the appropriate frame (so it can figure out its max width) then contentSize
should be representing the content.
Also: If textView is defined as weak
, the text view will be gone on the next line (as ARC adds a release and the optimizer moves it up). They announced this optimization change for Debug (-O0) builds during WWDC.
UITextView Content Size too Short
I had this same problem using storyboards in iOS7.
My solution was to add this code:
CGRect newTextViewFrame = self.textView.frame;
newTextViewFrame.size.width = self.textView.contentSize.width + self.textView.contentInset.right + self.textView.contentInset.left;
newTextViewFrame.size.height = self.textView.contentSize.height + self.textView.contentInset.top + self.textView.contentInset.bottom;
self.textView.frame = newTextViewFrame;
in the viewDidAppear:
view life cycle method and it was immediately sized to fit it's contents. Unfortunately, this resize happens after the view has already appeared which means that the user sees it happening.
Example:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
CGRect newTextViewFrame = self.textView.frame;
newTextViewFrame.size.width = self.textView.contentSize.width + self.textView.contentInset.right + self.textView.contentInset.left;
newTextViewFrame.size.height = self.textView.contentSize.height + self.textView.contentInset.top + self.textView.contentInset.bottom;
self.textView.frame = newTextViewFrame;
}
The height of textView will never grow with its contentSize in Xcode 5 & iOS 7
I think you are presenting popOverView using
[popOverView presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:NO];
Please change ArrowDirections from UIPopoverArrowDirectionUp to UIPopoverArrowDirectionAny
Resizing UITextView - Height not adjusting
Here was the answer to my issue. At some point I had checked off Autolayout on my view. This effectively locked the view and didn't allow me to adjust the frame size.
If you are seeing a similar issue that the frame is not resizing try the following:
- Go to interface builder and open the view
- Click on the file inspector
- Deselect auto-layout.
This resolved my issue.
change UITextView height programmatically with the text
i think you need to do :
CGRect frame = textViewA1.frame;
frame.size.height = textViewA1.contentSize.height;
textViewA1.frame = frame;
after the addsubview:
[self.view addSubview: self.textView];
Related Topics
Is There a Good Charting Library For Iphone
Difference Between Uiviewcontentmodescaleaspectfit and Uiviewcontentmodescaletofill
Detecting the Call Events in Ios
Getting iOS System Uptime, That Doesn't Pause When Asleep
How to Load a Uiimage from a Url
Add "...Read More" to the End of Uilabel
How to Programmatically Check Whether a Keyboard Is Present in iOS App
Changing Root View Controller of a iOS Window
Error Opening iOS Simulator with iOS 8 Beta Version: "Unable to Boot the iOS Simulator"
Make Uinavigationbar Transparent
#Warning: C-Style For Statement Is Deprecated and Will Be Removed in a Future Version of Swift
Nsurlconnection and Basic Http Authentication in Ios
How to Detect If App Is Being Built For Device or Simulator in Swift
Closure Cannot Implicitly Capture a Mutating Self Parameter
How to Compress/Resize Image on iOS Before Uploading to a Server