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

后端 未结 8 2254
被撕碎了的回忆
被撕碎了的回忆 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:19

    I see three options here.

    First, make label's size big enough to hold any text. That's most simple, but does not always work well - depends on its surrounding views.

    Second, Label can adapt size of the font for longer text (adjustsFontSizeToFitWidth property). This is often not desirable, different fonts in elements might look ugly.

    Last option is to programmatically resize the label according to its currently holding text. To calculate the size required to hold the text with current font use something like this:

    CGSize textSize = [[someLabel text] sizeWithFont:[someLabel font] forWidth:someLabel.bounds.size.width lineBreakMode:UILineBreakModeWordWrap];
    

提交回复
热议问题