IOS: How to set the UILabel frame according to its text?

I want to create a functionality that means to set the UILabel frame according to its text means that when the text changes, its frame changes? If so, please share a link or any idea to develop this.

Thanks in advance.

+6
source share
4 answers

If you want to know the desired height for a certain width , you can use the following code:

 NSString *yourString = @"My great text o0"; CGSize s = [yourString sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap]; // s.height is your your height 

Read more here

+3
source
 label.text = @"some text of random length"; [label sizeToFit]; 

If the text can be more than 1 line, add label.numberOfLines = 0; before calling sizeToFit;

+20
source

try it

 NSString *sample = @"..."; CGSize txtSz = [sample sizeWithFont:[UIFont fontWithName: @"Helvetica" size: 16]]; CGRect lblFrame = CGRectMake(10,50, txtSz.width, txtSz.height); yourLabel.frame = lblFrame; 
+5
source

It's 2016 and sizeWithFont long gone.

Now in Swift 3 use:

 let text = "Random Text" let size = (text as NSString).size(attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 50)]) let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height)) 
+3
source

Source: https://habr.com/ru/post/896194/


All Articles