0

hope you are doing good.

I am setting a label and adjusting its frame ..

UILabel *mylabel=[[UILabel alloc]init];
    mylabel.Text=@"This is my label";
    mylabel.frame=CGRectMake(10,10,200,21);

now if I change the Label's text from any string set by me like this

NSString *mystring=@"This is my first string that is to be assigned to my label dynamilcally";
mylabel.Text=mystring;
mylabel.frame.size.width=mystring.length;

but nothing happens. The width of the label remains 200, as I set while at the time of initialisation.

This will also need to get the width of the mystring . How to get that?

Thank in anticipation for helping me a lot.

iOmi
  • 625
  • 10
  • 24

1 Answers1

1

[myLabel sizeToFit] if you need it on one line. For multiple line labels you can use NSString's sizeWithFont:constrainedToSize:lineBreakMode: function to get size of your string and use it to modify your label's height & width.

e.g. code that gives you height for multiline label with fixed width of 200px:

CGSize textSize = { 
    200.0,   // limit width
    20000.0  // and height of text area
}; 

CGSize size = [descriptionString sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = size.height < 36? 36: size.height; // lower bound for height

CGRect labelFrame = [myLabel frame];
labelFrame.size.height = height;
[myLabel setFrame:labelFrame];
[myLabel setText:descriptionString];
Alexander
  • 8,117
  • 1
  • 35
  • 46