views:

905

answers:

2

Hello ist there a way to split a String for UITableView at a specific line to put the "rest" (the second part of the data) in an own cell

NSString *data;    
CGsize *size = [data sizeOfStringWithFont:[UIFont systemFontOfSize:14] constrainToWidth:280.0];

if the size.height e.g. is greater than 1500 i want to split the string at this line position!

thank you

A: 

Use "constrainedToSize" (instead of just to width) and render as much as you can.

If you really want to take exactly the text that would not fit, you're going to have to do essentially a search, adding a word at a time and then doing the size check to see how high you have gotten. You could start out with a rough estimate by doing the whole string constrained to something only one line high with boundless width (say 999999) and then divide up the width into however many rows you are wishing to allow to get a rough starting point for adding/removing words from the string (it will not be exact because of word wrapping).

Fundamentally though it seems wierd to take the leftover text and put it in another cell. Are you really sure you don't simply want to change the height of the cell with the text to allow it to fit the whole thing?

Kendall Helmstetter Gelner
+1  A: 

I think Kendall has the right idea, but the constrained sizes should be reversed to get the exact height based on word wrapping. Take a sample CGSize that is the same width as your cell, but with a height larger than the max height you expect. In the sample code below, textSize will contain the height of your string as it would appear in your cell with an unbounded height.

CGSize sz = CGSizeMake (
   yourCellWidth,
   999999.0f );

CGSize textSize = [yourString sizeWithFont:yourCellfont 
                  constrainedToSize:sz
                  lineBreakMode:UILineBreakModeWordWrap];

If the height is greater than 1500, you could start picking off substrings (substringWithRange) from the end and measuring them like above until you get something >= the remainder above 1500 that was returned by textSize.

Christopher Scott