简体   繁体   English

自动收缩多行标签

[英]Auto shrink label with multiple lines Swift

I am making a app without using storyboard. 我在不使用情节提要的情况下制作应用。 The app has a long text so I can't get enought space on one line. 该应用程序的文字很长,所以我一行上没有足够的空间。 The app is for both iPad and iPhone. 该应用程序适用于iPad和iPhone。 The adjustSizeToFit = true does not work, is there a metode to adjust size of label with multiple lines? adjustSizeToFit = true不起作用,是否有一个方法来调整多行标签的尺寸?

There is no property on UILabel called adjustSizeToFit . UILabel上没有称为adjustSizeToFit属性。 Are you sure you didn't mean adjustsFontSizeToFitWidth ? 您确定您不是指adjustsFontSizeToFitWidth吗? Which if you look at the documentation, says: 如果您查看文档,会说:

Normally, the label text is drawn with the font you specify in the font property. 通常,标签文本是使用您在font属性中指定的字体绘制的。 If this property is set to true, however, and the text in the text property exceeds the label's bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached. 但是,如果将此属性设置为true,并且text属性中的文本超过标签的边界矩形,则接收方将开始减小字体大小,直到字符串适合或达到最小字体大小为止。 In iOS 6 and earlier, this property is effective only when the numberOfLines property is set to 1. 在iOS 6和更早版本中,仅当numberOfLines属性设置为1时,此属性才有效。

Which I'm not sure is what you wanted. 我不确定您想要什么。

If you wanted a UILabel with an arbitrary number of lines, where the text is contained within a certain width, continue reading: 如果您希望UILabel具有任意数量的行(其中文本包含在一定宽度内),请继续阅读:

What you do will depend on whether you're using AutoLayout or not: 您的操作将取决于您是否使用自动版式:

Not AutoLayout 不是自动版式

Just use: 只需使用:

let size = label.sizeThatFits(CGSize(width: myWidth, height: CGFloat.max))
// CGFloat.max, because we don't want to limit the UILabel's height.
label.frame.size = size

AutoLayout 自动版式

Firstly, you should set numberOfLines to zero. 首先,应将numberOfLines设置为零。 Secondly, you need to tell AutoLayout how long each line can be, this doesn't default to the width of the label. 其次,您需要告诉AutoLayout每行可以多长时间,这并不是默认的标签宽度。 For this you need a UILabel subclass: 为此,您需要一个UILabel子类:

class myLabel : UILabel {
    override func layoutSubviews() {
        // 1. Get the label to set its frame correctly:
        super.layoutSubviews()

        // 2. Now the frame is set we can get the correct width 
        // and set it to the preferredMaxLayoutWidth.
        self.preferredMaxLayoutWidth = self.frame.width
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM