根据包含的文本设置UILabel的行数 - Objective C和/或Swift

时间:2014-09-01 11:07:18

标签: objective-c swift height uilabel lines

我正在尝试将一些随机文字显示在UILabel中,当然除了宽度之外我什么都没有。有没有办法根据其中包含的文字设置UILabel的高度和/或行数?

谢谢;)

5 个答案:

答案 0 :(得分:9)

myUILabel.numberOfLines = 0;
myUILabel.text = @"Pass random text here";
[myUILabel sizeToFit];

答案 1 :(得分:4)

或者(如果你需要特定宽度和字体大小的标签高度,你可以用它来计算它):

func getStringHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat {

    let font = UIFont.systemFontOfSize(fontSize)
    let size = CGSizeMake(width,CGFloat.max)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .ByWordWrapping;
    let attributes = [NSFontAttributeName:font,
        NSParagraphStyleAttributeName:paragraphStyle.copy()]

    let text = mytext as NSString
    let rect = text.boundingRectWithSize(size, options:.UsesLineFragmentOrigin, attributes: attributes, context:nil)
    return rect.size.height  
}

你需要这个用于Swift还是用于Objective C?

答案 2 :(得分:1)

您可以使用NSString UIKIT Addition方法

- (CGSize)sizeWithFont:(UIFont *)font
     constrainedToSize:(CGSize)size
         lineBreakMode:(NSLineBreakMode)lineBreakMode

计算高度。类似的东西。

CGSize yourLabelSize = [@"Your very long text" sizeWithFont:yourFont constrainedToSize:CGSizeMake(desiredMaximumWidth, 2000) lineBreakMode:NSLineBreakByWordWrapping];

理解constrainedToSize参数非常重要。您必须传递宽度为CGSizedesired maximum的{​​{1}}。在标签上使用相同的maximum possible height。别忘了设置

UIFont

但该方法已在[yourLabel setNumberOfLines:0]; 中弃用,因此您必须使用

iOS 7

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context 会给你高度

希望它能帮到你......

答案 3 :(得分:1)

适用于Swift 4.0

func getStringHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat {

    let font = UIFont.systemFont(ofSize: fontSize)
    let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byWordWrapping;
    let attributes = [NSAttributedStringKey.font:font,
                      NSAttributedStringKey.paragraphStyle:paragraphStyle.copy()]

    let text = mytext as NSString
    let rect = text.boundingRect(with: size,
                                options:.usesLineFragmentOrigin,
                                attributes: attributes,
                                context:nil)
    return rect.size.height
}

答案 4 :(得分:0)

let l = UILabel()
l.numberOfLines = 0
l.layer.frame.size.width = self.view.frame.width - 40 /*padding(20 + 20)*/

l.font = UIFont(name: "BwModelica-Bold", size: 16.0)

l.text = "Random Any length Text!!"

let noOfLines = ceil(l.intrinsicContentSize.width) / l.frame.width)

let lbl_height = noOfLines * l.intrinsicContentSize.height

这将是您的Label的确切动态高度和行数。编码愉快!