How to determine the height of text in UITextView? - cocoa-touch

What is a good way to determine the current height of the content height in a UITextView?

Look in UIStringDrawing.h for various text measuring functions. You probably want something like:
[myTextView.text sizeWithFont:myTextView.font forWidth:myTextView.bounds.width lineBreakMode:UILineBreakModeWordWrap].height;
If you just want to know what the text view is using, then use:
[myTextView contentSize].height;

Related

How do I get the current font/font size at cursor in NSTextView?

Clarification: First, cursor = the insertion point cursor, not the mouse cursor.
Ok, I would like to return the font / font size / font color wherever the cursor is in the NSTextView. I tried using attribute:atIndex:effectiveRange:, but I failed because I got my variables all mixed up. I think it is what I need. Some example code would just be appreciated, returning the font. I think it will work the same for font size/color, I'll just have to substitute NSFontAttributeName for something else, right? Thanks in advance!
NSFont *font = [textView.textStorage attribute:NSFontAttributeName atIndex:textView.selectedRange.location effectiveRange:nil];
Should work for all getting the name.
What have you tried?
NSTextView has a method selectedRanges which returns the current selection(s) - just one of zero-length if there is just an insertion point.
NSTextView also has a property textStorage which returns back the instance of NSTextStorage which holds the text. An NSTextStorage inherits from NSMutableAttributedString, which inherits from NSAttributedString, and that has methods to obtain the attributes of the text.
Combined those two and you have your answer.
HTH

UItextview not expanding with constraints as expected

I am working with interface builder to create a xib. This xib has a uiview that contains a uitextview. Both are supposed to resize as the text in the uitextview changes. The constraints look a lot like this:
The pink UITextView pushes on the blue superview. The blue uiView has a minimum width of 189 px and a trailing constraint of at least 8px.
For the most part this works. Really long sections of text resize the two views to the fullest extent allowed as intended and if there are only one or two words, the views stay small. However, the problem is when you have a short sentence.
In this case, the views only expand to about 189px, and the text moves to the second line even though there is space to expand.
Here is what it looks like when you only put a few words in:
and here is a fully expanded box:
I have tried to make the trailing constraint have a lower priority than the others, and I have tried modifying the content hugging and compression resistance properties in many ways without success.
How can I make the views expand so that they fit the text content with the fewest number of lines? There are no restrictions on height, only on width.
Any help would be appreciated!
Get the new size of the textView using this method
CGSize sz = [_textView.text sizeWithFont:_textView.font]
in case that didn't work very well with the height,get the width you just got from the preivous method and use in the next method to get the appropriate height you need
- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
UITextView *textView = [[UITextView alloc] init];
[textView performSelectorOnMainThread:#selector(setAttributedText:)
withObject:text
waitUntilDone:YES];
CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
return size.height;
}
The key is to set the preferredMaxLayoutWidth to something big (320px sounds good. Your right constraint is going to limit it anyways).
You can do that in your code as
[self.label setPreferredMaxLayoutWidth:320];
Or from the Interface Builder as follows:
This way you'll see the label expanding as expected:
Have you tried the solution presented in this post?
Dynamic expand UITextView on ios 7
I believe you have to set your UITextView to sizeToFit
[YourUITextView sizeToFit];

Dynamic UITable Cell height

I have a UITableView with custom cells. I need to display Title, Address, Zip, Phone, Email, Website and Description in a Cell. All this information is coming from webserver. I am able to display the contents from the webserver. However, if any of the content is empty, there is a gap where that content should be, and if description is too long I am not able to display all the content. How can I change the height of cell according to the content from server? Please help.
For example : the contents is printing like:
Title
Address
Zip
Phone...
but, if Address is nil then it looks like:
Title
Zip
Phone...
I have the tableview:heightForRowAtIndexPath method but I am not able to update the cell height according to the cell contents.
Sorry for bad question format
Cells resizing can get pretty complicated, so I suggest you simply use a table view framework such as "Sensible TableView", where all the cells are automatically resized to fit contents. I believe they also now have a free version.
you can set the height of every cell with this delegate method
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = [yourArray objectAtIndex:indexPath.row];// here just use your data array which you get from server
CGSize mTempSize = [text sizeWithFont:[UIFont fontWithName:fontName size:fontSize] constrainedToSize:constrainedToSize lineBreakMode:UILineBreakModeWordWrap];
return mTempSize.height ;
}
i hope this help you...
Firstly you need to set the size of your labels according to it's text length. There are a number of sizeWithFont methods available to get size for a string. See Apple Developer Documentation
If you have single line labels you can use simplest of them – sizeWithFont:. But if you have multiline labels you should use – sizeWithFont:constrainedToSize:. This method lets you specify the maximum size you want the label be.
Secondly you have to return calculated height for your cell using tableView:heightForRowAtIndexPath:
Hope this helps you.
Your tableView:heightForRowAtIndexPath: call will need to tabe into account the missing data and how all the rest of the cell will be re-laid out to close the gap it leaves. So, your actual call will be non-trivial here.
The new facebook app does a neat trick here, though, to save you calling it every time. It calculates all of the cell heights in the background, just after downloading it, and before rendering the content to the user, storing it in the data store alongside the data itself. This means that the actual table cell rendering is really fast and slick as you don't need to re-layout/recalculate the cell height and layout on each app run/cell reuse.

How do I calculate the exact height of text using UIKit?

I'm using -[NSString sizeWithFont] to get the text height. The character 't' is clearly taller than 'm', but -sizeWithFont returns the same height for both these strings. Here's the code:
UIFont* myFont = [UIFont fontWithName:#"Helvetica" size:1000.0];
NSString* myStr = #"m";
CGSize mySize = [myStr sizeWithFont:myFont];
With 'm' as shown, it returns {834, 1151}. With myStr = #"t" instead, it's {278, 1151}. The smaller width shows up as expected, but not the height.
Does some other function wrap the text tightly? I'm ideally looking for something equivalent to Android's Paint.getTextBounds().
The information you get back from this method is basically the line height for the font (i.e., it's the ascent plus the descent for the font you've chosen). It's not based on individual characters, it's based on specific font metrics. You can get most of the information about a font's metrics from the UIFont class (e.g., the method -ascender gives you the height of the ascender for the font). Mostly, you will be dealing with the total amount of vertical space needed to draw the glyphs with the heights ascenders and the lowest descenders for that font. There is no way to get information about individual glyphs from UIFont. If you need this information, you'll have to look at the CoreText framework, which gives you a lot more flexibility in how you draw and arrange glyphs but is far, far more complicated to use.
For more information on dealing with text in your app, please se the Drawing and Managing Text section of the Text, Web, and Editing Programming Guide. It is also a good launching point for most of the frameworks and classes you'll need to deal with whether you go the UIKit or the CoreText route.
Hmmm... I assume you're only going to be working with individual characters then. sizeWithFont, as noted above, returns the height of the largest character of that font as the text field is going to be that height no matter what you do. You would be able to get the LARGEST height values (UIFont's CGFloat capHeight) however it looks like you're going to be working with all kinds of text
I would take a look at the CoreText framework. Start here and read away. Inevitably you're going to end up with something along the lines of this:
CGFloat GetLineHeightForFont(CTFontRef iFont)
{
CGFloat lineHeight = 0.0;
check(iFont != NULL);
lineHeight += CTFontGetLeading(iFont);
return lineHeight;
}

Truncating NSString to fit a particular width

I've got a variable-width-font NSString that has to fit inside a fixed size UIView. Currently, the string gets truncated and rendered.
I want to obtain the visible substring so I can append an elipsis (…) to it.
If you're using a UILabel, you can set the lineBreakMode to one of
UILineBreakModeHeadTruncation
UILineBreakModeTailTruncation
UILineBreakModeMiddleTruncation
The different positions refer to where the ... goes. You want UILineBreakModeTailTruncation.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/lineBreakMode