自动多线标签swift

时间:2015-10-30 07:22:15

标签: xcode swift label

我有一个标签,我在其中插入文字。标签有一个大小但我的问题是:

当我在标签中插入文字时,如果文字长于标签'尺寸出现" ...."在标签上;例如:

如果我想要在标签中插入的完整字符串是:"hello world how are you?"

标签中的

我看到了"hello world..."

我希望该标签自动包装。

出于这个原因,我做了这个,但它没有工作:

label!.textAlignment = NSTextAlignment.Center;
label!.numberOfLines = 0;
label!.font = UIFont.systemFontOfSize(16.0);
label!.text = "hello world how are you?"

我哪里错了?

4 个答案:

答案 0 :(得分:13)

  label.lineBreakMode = .byWordWrapping
  label.numberOfLines = 0;

或调整以下字体大小以适合整个字符串

label.adjustsFontSizeToFitWidth = true

答案 1 :(得分:1)

您没有提及是否使用堆栈视图。如果将UILabel放在堆栈视图中,正常的方法(由good4pc提供)将无法正常工作。

如果您使用的是堆栈视图:

制作一个可行的自定义标签类。我在下面粘贴了一个 - 只需创建一个新的swift文件并将此代码放入其中。调用swift文件" MultilineLabelThatWorks"。然后,将标签定义为" MultilineLabelThatWorks"而不是" UILabel"

import UIKit

class MultilineLabelThatWorks : UILabel {
override func layoutSubviews() {
    super.layoutSubviews()
    preferredMaxLayoutWidth = bounds.width
    super.layoutSubviews()
}
}

现在您可以将其设置为包装文本,如good4pc所讨论的那样,它将正确包装。

答案 2 :(得分:1)

我所做的是使用UILabel课程。

创建标签:

 let multiLabel = LabelClass(text: "hello world how are u?", labelWidth: 250, pos: CGPoint(x: size.width / 2, y: size.height / 2))
        addChild(multiLabel)

您现在已经引用了您的LabelClass文件。这是代码:

import SpriteKit

class GameSceneLabel : SKNode {


    //props
    var labelWidth:Int {didSet {update()}}
    var labelHeight:Int = 0
    var text:String {didSet {update()}}
    var fontName:String {didSet {update()}}
    var fontSize:CGFloat {didSet {update()}}
    var pos:CGPoint {didSet {update()}}
    var fontColor:UIColor {didSet {update()}}
    var leading:Int {didSet {update()}}
    var alignment:SKLabelHorizontalAlignmentMode {didSet {update()}}
    var dontUpdate = false
    var shouldShowBorder:Bool = false {didSet {update()}}
    //display objects
    var rect:SKShapeNode?
    var labels:[SKLabelNode] = []

    init(text:String, labelWidth:Int, pos:CGPoint, fontName:String="ChalkboardSE-Regular",fontSize:CGFloat=20,fontColor:UIColor=UIColor.white,leading:Int? = nil, alignment:SKLabelHorizontalAlignmentMode = .center, shouldShowBorder:Bool = false)
    {
        self.text = text
        self.labelWidth = labelWidth
        self.pos = pos
        self.fontName = fontName
        self.fontSize = fontSize
        self.fontColor = fontColor
        self.leading = leading ?? Int(fontSize)
        self.shouldShowBorder = shouldShowBorder
        self.alignment = alignment


        super.init()

        self.update()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //if you want to change properties without updating the text field,
    //  set dontUpdate to false and call the update method manually.
    func update() {
        if (dontUpdate) {return}
        if (labels.count>0) {
            for label in labels {
                label.removeFromParent()
            }
            labels = []
        }
        let separators = NSCharacterSet.whitespacesAndNewlines
        let words = (text as NSString).components(separatedBy: separators)
        var finalLine = false
        var wordCount = -1
        var lineCount = 0
        while (!finalLine) {
            lineCount+=1
            var lineLength = CGFloat(0)
            var lineString = ""
            var lineStringBeforeAddingWord = ""

            // creation of the SKLabelNode itself
            let label = SKLabelNode(fontNamed: fontName)
            // name each label node so you can animate it if u wish
            label.name = "line\(lineCount)"
            label.horizontalAlignmentMode = alignment
            label.fontSize = fontSize
            label.fontColor = fontColor

            while lineLength < CGFloat(labelWidth)
            {
                wordCount+=1
                if wordCount > words.count-1
                {
                    //label.text = "\(lineString) \(words[wordCount])"
                    finalLine = true
                    break
                }
                else
                {
                    lineStringBeforeAddingWord = lineString
                    lineString = "\(lineString) \(words[wordCount])"
                    label.text = lineString
                    lineLength = label.frame.width
                }
            }
            if lineLength > 0 {
                wordCount-=1
                if (!finalLine) {
                    lineString = lineStringBeforeAddingWord
                }
                label.text = lineString
                var linePos = pos
                if (alignment == .left) {
                    linePos.x -= CGFloat(labelWidth / 2)
                } else if (alignment == .right) {
                    linePos.x += CGFloat(labelWidth / 2)
                }
                linePos.y += CGFloat(-leading * lineCount)
                label.position = CGPoint(x:linePos.x , y:linePos.y )
                self.addChild(label)
                labels.append(label)
            }

        }
        labelHeight = lineCount * leading
        showBorder()
    }
    func showBorder() {
        if (!shouldShowBorder) {return}
        if let rect = self.rect {
            self.removeChildren(in: [rect])
        }
        self.rect = SKShapeNode(rectOf: CGSize(width: labelWidth, height: labelHeight))
        if let rect = self.rect {
            rect.strokeColor = UIColor.white
            rect.lineWidth = 1
            rect.position = CGPoint(x: pos.x, y: pos.y - (CGFloat(labelHeight) / 2.0))
            self.addChild(rect)
        }

    }
}

在这里,您可以设置您的位置,字体,字体大小,颜色和所需的一切。

如果有帮助,请告诉我

答案 3 :(得分:1)

确保您没有固定标签的高度。 那么你只需要这两行:

labelTitle?.numberOfLines = 0
labelTitle?.lineBreakMode = NSLineBreakMode.ByWordWrapping