How do I make the text of one label node take up 2 lines?

593 views Asked by At

I have this text below that is too long to fit on the screen when it runs. How can I make this 2 lines rather than one?

myLabel.text = "The weather today is going to be partly cloudy with a chance of rain"
3

There are 3 answers

0
Leo Dabus On BEST ANSWER

edit/update:

**For iOS 11 or later you can set numberOfLines, lineBreakMode, and preferredMaxLayoutWidth properties. attributedText is supported as well **

Original answer


You can create your own method to display multi line text as follow:

import SpriteKit

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        displayMultiLineTextAt(CGRectGetMidX(self.frame) - 100, y: CGRectGetMidY(self.frame) + 50, align: SKLabelHorizontalAlignmentMode.Left, lineHeight: 20.0, text: "Welcome to StackOverFlow!\nThe weather today is going to\nbe partly cloudy with a chance\nof rain.")
    }
    func displayMultiLineTextAt(x: CGFloat, y: CGFloat, align: SKLabelHorizontalAlignmentMode, lineHeight: CGFloat, text: String) {
        let textNode = SKNode()
        textNode.position = CGPointMake(x, y)
        var lineAt: CGFloat = 0
        for line in text.componentsSeparatedByString("\n") {
            let labelNode = SKLabelNode(fontNamed: "Arial")
            labelNode.fontSize = 14
            labelNode.horizontalAlignmentMode = align
            labelNode.fontColor = SKColor(hue: 1, saturation: 1, brightness: 1, alpha: 1)
            labelNode.position = CGPointMake(0, lineAt)
            labelNode.text = line
            textNode.addChild(labelNode)
            lineAt -= lineHeight
        }
        scene!.addChild(textNode)
    }
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        /* Called when a touch begins */
    }
    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}
2
LinusGeffarth On

#1
Set the number of lines:

myLabel.numberOfLines = 2 //set to 0 if you want it to automatically decide based on how many line breaks you add in step 2

#2
Add line breaks in your text using \n or \r:

myLabel.text = "The weather today is going to\nbe partly cloudy with a chance of rain"

Hope that helps :)

Edit

You should have clarified that you are using a SKLabelNode rather than a normal UILabel. Here is what you could do since SKLabelNodes do not support multiple lines.

  • create a new view
  • add label #1 to the view
  • add another label (#2) to the view, place it below label #1
  • split the sentence into two parts, add first part to label #1 and second to label #2
2
zmgift On
  • myLabel.numberOfLines = 2 //or set to 0
  • make sure myLabel.frame.size.height is enough