UILabel is not auto-shrinking text to fit label size

后端 未结 17 648
感动是毒
感动是毒 2020-12-04 06:53

I have this strange issue, and im dealing with it for more than 8 hours now.. Depending on situation i have to calculate UILabels size dynamically,
e.g

17条回答
  •  囚心锁ツ
    2020-12-04 07:44

    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 THE WIDTH CONSTRAINTS FOR LABEL.
        CGFloat constrainedWidth = 240.0f;//YOU CAN PUT YOUR DESIRED ONE,THE MAXIMUM WIDTH OF YOUR LABEL.
     //CALCULATE THE SPACE FOR THE TEXT SPECIFIED.
        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;//JUST TO SUPPORT MULTILINING.
    

提交回复
热议问题