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
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With