30

There was a method

- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment;

which I must replace now for iOS 7. I get as far as

NSDictionary *attributes = @{NSFontAttributeName: font};
[self drawInRect:rect withAttributes:attributes];

but how to specify the line break mode like word wrap? I searched documentation of Attributed string drawing symbols but no mention of line break mode. Is this automartically always word-wrap?

openfrog
  • 40,201
  • 65
  • 225
  • 373

2 Answers2

58

You need to create a paragraph style.

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];

NSDictionary *attributes = @{NSFontAttributeName: font, NSParagraphStyleAttributeName: style};
[self drawInRect:rect withAttributes:attributes];

More information here: https://developer.apple.com/documentation/uikit/nsparagraphstyle?language=objc

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
  • I think you can also use `[[NSMutableParagraphStyle alloc] init]` instead of the mutable copy. – zavié Dec 08 '15 at 17:44
  • @zavié mutableCopy was used because he wanted to instantiate a NSMutableParagraphStyle based on defaultParagraphStyle. If you init it as NSMutableParagraphStyle.default it turns into a NSParagraphStyle instead. So you have to turn it into a mutable by calling mutableCopy. – Allan Jul 08 '22 at 18:02
9

In Swift 5:

let style = NSMutableParagraphStyle()
style.lineBreakMode = .byWordWrapping

let attributes: [NSAttributedString.Key: Any] = [
   .font: font,
   .paragraphStyle: style
]
kelin
  • 11,323
  • 6
  • 67
  • 104
Phlippie Bosman
  • 5,378
  • 3
  • 26
  • 29