views:

780

answers:

3

In Cocoa, there is a method (lineBreakBeforeIndex:withinRange:) on NSAttributedString to find appropriate line breaks in a piece of text.

Since NSAttributedString does not exist on the iPhone, does anyone have any suggestions for similar functionality?

Edit: Realized that I'm really looking for a word-wrap algorithm. For example, I want the text to wrap at 80 characters; where do I place line breaks so that words are not split over two lines?

Edit: An example will probably help. Say I have the following lines:
Here is line 1 that probably won't even be 80 characters long.
Here is another line with different text that is longer but not by much.

I would like to turn that into something like:
Here is line 1 that probably
won't even be 80 characters
long.
Here is another line with
different text that is
longer but not by much.

Edit: I'm looking to place this text in a UITextView so that additional edits can be made (very similar to a quoted reply with emails)

A: 
NSString *newString = [oldString stringByReplacingOccurrencesOfString:@"\n" withString:@"<br />"];

That will find all your line breaks and replace it with a "
" tag. Just edit it for your own needs. :)

Brandon Schlenker
Sorry, I didn't phrase the question very well. Hopefully my edit makes it more clear.
hjon
A: 

There is already a question about word-wrap algorithms: http://stackoverflow.com/questions/17586/best-word-wrap-algorithm

hjon
This linked question was the closest to what I was looking for, since I don't just need to display the data with wrapping, but need to the user to edit it further.
hjon
+1  A: 

Depends what do you need it for, you can line break text in UILabel (e.g. if you are doing multiline text for example inside UITableViewCell).

See:

http://www.doubleencore.com/blog/2009/01/18/iphone-dev-tip-using-uilabels-numberoflines-adjustsfontsizetowidth/

http://developer.apple.com/iPhone/library/documentation/UIKit/Reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instm/UILabel/textRectForBounds:limitedToNumberOfLines:

http://blog.sallarp.com/iphone-uilabel-multiline-dynamic-height/

This method specifies the size (a rect) into which the text need to fit - probably you can update it to calculate what size is 80 characters with your font then create rectangle of that size then fit the text in it.

stefanB
Unfortunately, I want to place this in a UITextView so additional edits can be made (similar to quoted replies in an email).
hjon