Pyetras
Pyetras

Reputation: 1502

Breaking NSString into lines (to fit desired width)

I'm trying to get a NSString broken into lines to fit a desired width (as it would happen inside sizeWithFont:constrainedToSize:). Is there a better way to do this than guessing where the breaks would happen in sizeWithFont?

Upvotes: 6

Views: 2564

Answers (4)

alexey
alexey

Reputation: 8480

NSLayoutManager is available since iOS 7. Documentation is here.

Upvotes: 1

Martin Gordon
Martin Gordon

Reputation: 36399

Update: Based on the comment below (you can draw the string, but can't draw a background to cover the string), I think your best bet would be to use a UIWebView and use CSS to draw your background.


The NSString UIKit Additions might fit your needs, particularly

- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font 
       lineBreakMode:(UILineBreakMode)lineBreakMode;

and/or

- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font 
       lineBreakMode:(UILineBreakMode)lineBreakMode
           alignment:(UITextAlignment)alignment;

Upvotes: 1

Noah Witherspoon
Noah Witherspoon

Reputation: 57149

If NSLayoutManager is indeed unavailable, you may be stuck with a more inefficient solution: starting with the first word of the string, appending each subsequent word and using the sizeWithFont:(etc.) method on the resulting string. When the height of the returned CGSize changes, the most recently appended word was the one that caused the line break, and you can thus split the string there.

Upvotes: 2

Joshua Nozzi
Joshua Nozzi

Reputation: 61238

Update: This apparently only applies on the Mac platform. Though NSLayoutManager is specifically referenced in the iPhone's String Drawing Guide (as of December, 2009), neither it nor NSAttributedString are available on the iPhone platform. Sorry for the noise.

Original Response

NSLayoutManager is your friend if you're looking to divide up the string itself into lines of a certain width, with a given set of attributes (ie, you need to know the actual places where the string is wrapped).

If you're only looking to wrap lines when drawing and you don't care where, NSAttributedString's (AppKit Additions) methods -drawInRect: or -drawWithRect:options: will do just fine.

Upvotes: 1

Related Questions