Autosize UILabel
Asked Answered
L

4

13

Is there a way to auto size a UILabel? given size 40 x 40 the text font size would adjust based on the number of characters.

Luong answered 14/7, 2010 at 7:53 Comment(0)
I
26

You can use the adjustFontSizeToFitWidth property. So something like this.

UILabel *myLabel = [[UILabel alloc] init];
[myLabel setAdjustsFontSizeToFitWidth:YES];

In Interface Builder there is a check box on the Label Attributes screen to allow you to adjust the font size to fit the label as well.

Inhumane answered 14/7, 2010 at 7:56 Comment(2)
No problem. Sorry, the sample code used to read adjustFontSizeToWidth, but it should be adjustFontSizeToFitWidth. I corrected it.Inhumane
You skip one letter in AdjustS: [myLabel setAdjustsFontSizeToFitWidth:YES];Emulous
M
0

uhm, did you check out the UILabel API http://developer.apple.com/iphone/library/documentation/uikit/reference/UILabel_Class/Reference/UILabel.html there's a neat property called adjustsFontSizeToFitWidth

Maice answered 14/7, 2010 at 7:55 Comment(1)
no worries :) sorry, that I didn't provide any sample code. Besides the Apple Docs are very valuable and useful.Maice
A
0

With autolayout design concept, do not set height constraints for UILabel and set no. of lines as 0.

Autolayout automatically take care of dynamic height of label according to text of label. If label has single line text then it will occupy single line space only. And if label has more than one line then it will resize label according to text size and number of lines required to display text.

Set number of lines zero for dynamic text information, it will be useful when your text are varying.

Programatically (Swift 4)

var label = UILabel()
let stringValue = "iOS\nmultiline\nlabel\nin\nInterface\nbuilder"
label.text = stringValue
label.numberOfLines = 0 // Set 0, if number of lines not specified.
label.lineBreakMode = .byTruncatingTail // or .byWrappingWord
label.minimumScaleFactor = 0.8 . // It is not required but nice to have a minimum scale factor to fit text into label frame

Using Inetrface Builder

enter image description here

Note: It is not required to set Minimum Font Scale, but nice to have a minimum scale factor to fit text into label frame.

Ref: UILabel - numberOfLines

Abirritate answered 21/6, 2017 at 12:11 Comment(0)
C
0

Its better to use Intrinsic content and compression resistance priorities to adjust the size of label w.r.t content.

Cosmorama answered 6/2, 2020 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.