Tommy
Tommy

Reputation:

Best way to determine word wrap of a NSString in a UILabel

I have a line like:

 -Image-  This is simply a test 
 -Image-  but I want to know how
to separate the two lines.  What
to do here?

The best way I could figure to implement on the iPhone is:

UIImageView  UILabel1
             UILabel1
UILabel2

If there's an easier way to do this with the UI elements - i'm all ears. Otherwise, I'm trying to figure out where the text ends in UILabel1 without trial and error using sizeWithFont.

A more intricate way would be to find the size of each character at that font size using sizeWithFont, and add it all together (figuring out where the word wrap on line 1 of UILabel1, and then on Line2 as well). This feels like a hard way to solve an easy problem. Anyone know of the easy way?

Upvotes: 1

Views: 2120

Answers (2)

oxigen
oxigen

Reputation: 6263

NSString s = @"First Line \n second line \n lastline ";

Upvotes: 1

duncanwilcox
duncanwilcox

Reputation: 3498

Perhaps this is not the answer you are looking for, but this sort of layout is easier done with a WebView.

From an efficiency point of view, UILabel text rendering is implemented via WebViews anyway.

This article by Craig Hockenberry suggests that trying to

use metrics and line breaking that [match] those used in UILabel’s implementation [...] is far from perfect

and also confirms that UILabels use WebViews under the hood (it's also easily seen in a Shark dump of a text-intensive app).

Upvotes: 1

Related Questions