How to adjust and make the width of a UILabel to fit the text size?

后端 未结 8 2230
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 06:01

In my project, there is a UILabel with text. The font size is 16pt. The text contents are changed depending on different cases. I hope it can automatically adju

8条回答
  •  春和景丽
    2020-12-13 06:39

    Here's how to do it, suppose the following messageLabel is the label you want to have the desired effect. Now, try these simple line of codes:

        // Set width constraint for label; it's actually the width of your UILabel
        CGFloat constrainedWidth = 240.0f;
        // Calculate space for the specified string
        CGSize sizeOfText = [yourText sizeWithFont:yourFont constrainedToSize:CGSizeMake(constrainedWidth, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
        UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,20,constrainedWidth,sizeOfText.height)];
        messageLabel.text = yourText;
        messageLabel.numberOfLines = 0;// This will make the label multiline
    

提交回复
热议问题