\n not working in Sklabel SpriteKit

前端 未结 4 2227
滥情空心
滥情空心 2021-02-20 10:53

I have been using the following code in my game. The Problem is that i am unable to make multi-line label in spritekit as i was able to do using CCLabelTTF...... Can Somebody he

4条回答
  •  爱一瞬间的悲伤
    2021-02-20 11:42

    Like a lot of others I also needed a fix to this problem. My approach was a lot simpler than Chris' solution. I have made a subclass of SKLabelNode called NORLabelNode.

    It's available at GitHub and there is also a cocoapod available.

    It simply creates a set of SKLabelNodes and use these as subnodes. If you want to implement something similar yourself the main gist is this method:

    - (NSArray *)labelNodesFromText:(NSString *)text{
        NSArray *substrings    = [text componentsSeparatedByString:@"\n"];
        NSMutableArray *labelNodes    = [[NSMutableArray alloc] initWithCapacity:[substrings count]];
    
        NSUInteger labelNumber    = 0;
        for (NSString *substring in substrings) {
            SKLabelNode *labelNode    = [SKLabelNode labelNodeWithFontNamed:self.fontName];
            labelNode.text    = substring;
            labelNode.fontColor    = self.fontColor;
            labelNode.fontSize    = self.fontSize;
            labelNode.horizontalAlignmentMode    = self.horizontalAlignmentMode;
            labelNode.verticalAlignmentMode    = self.verticalAlignmentMode;
            CGFloat y    = self.position.y - (labelNumber * self.fontSize * self.lineSpacing);
            labelNode.position    = CGPointMake(self.position.x, y);
            labelNumber++;
            [labelNodes addObject:labelNode];
        }
    
        return [labelNodes copy];
    }
    

    The above is somewhat simplified as the labels also inherit most of the other properties from their parent.

    The linespacing can be altered through a CGFloat property. Apart from this is works just like an ordinary SKLabelNode and you can change text, color, font, fontSize etc. on the fly whenever you feel like.

提交回复
热议问题