Tested with 0.99.4; should work with other versions though
Commonly, we need to have a multi-line text, e.g. on a dialog. Here's how to do it on two ways.
This is the easiest approach. Most people generally use :
CCLabel* myLabel = [CCLabel labelWithString: @"A Text" fontName: @"Arial" fontSize: 16];
However, there is another method, which does what we need:
CCLabel* myLabel = [CCLabel labelWithString:@"A text" dimensions: CGSizeMake(200, 300) alignment:UITextAlignmentLeft fontName:@"Arial" fontSize:16];
This will result in a CCLabel which will occupy a 200×300 rect. Note you can change the alignment also (UITextAlignmentLeft, UITextAlignmentRight or UITextAlignmentCenter).
Most of times this is what we need. But sometimes, we need to use a CCBitmapFontAtlas…
LongJohnnyE was kind enough to share his solution
-(void) setTipString:(NSString*)str { NSInteger lineChars = 0; BOOL isSpace = NO; NSInteger index = 0; NSInteger numLines = 0; NSInteger LINE_LENGTH = 30; // this is each line's length, in characters NSMutableString *line = [NSMutableString stringWithCapacity:LINE_LENGTH]; while (index <= [str length]) { if(index == [str length]) { CCBitmapFontAtlas *tip = [[CCBitmapFontAtlas bitmapFontAtlasWithString:[NSString stringWithString:line] fntFile:@"text.fnt"] retain]; [tip setPosition: ccp(30,210 - 20 * numLines)]; [self addChild:tip]; [tip release]; return; } NSString *tmp = [str substringWithRange:NSMakeRange(index, 1)]; [line appendString:tmp]; if([tmp isEqual:@" "]) isSpace = YES; else isSpace = NO; if(lineChars >= LINE_LENGTH && isSpace) { CCBitmapFontAtlas *tip = [[CCBitmapFontAtlas bitmapFontAtlasWithString:[NSString stringWithString:line] fntFile:@"text.fnt"] retain]; [tip setPosition: ccp(30,210 - 20 * numLines)]; [self addChild:tip]; [tip release]; lineChars = -1; [line setString:@""]; numLines++; } lineChars++; index++; } }
This is the basic snippet, which will create and add to self CCBitmapFontAtlas. You can adapt this to your own need, e.g. adding to a array each line, so you can reverence it later.
I should not use it, unless you need to use CCBitmapFontAtlas for something, like getting each letter. (I used it to make a dialog, with a typewriter effect).
Again, I'd rather use the CCLabel approach most of times, but it's good to know there's another approach if needed. I adapted the setTipString code to 0.99.4 version from http://johnehartzog.com/2009/06/create-multi-line-labels-with-cocos-2d-iphone/
I took setTipString method from http://johnehartzog.com/2009/06/create-multi-line-labels-with-cocos-2d-iphone/
Also, it's always good to look the documentation and API reference (http://www.cocos2d-iphone.org/api-ref/latest-stable/) ;D