Monday, July 16, 2012

Find size of rect to fit a string?


This has been a popular question of all time. Developers will face it sooner or later. You have a string which you want to display in your UILabel, but you want to keep the size of UILabel dynamic, you don't want to hard code its bounding rectangle because say, your string is dynamic.

NSString *myString=@"This is a dynamic string";// It will probably change after some event happens.


  UIFont *myFont=[UIFont fontWithName:@"Helvetica" size:10];
  CGSize size = [myString sizeWithFont:myFont forWidth:300 lineBreakMode:UILineBreakModeWordWrap];


Create the CGRect with the size calculated above.

  CGRect a=CGRectMake(5050, size.width, size.height);


Now you can create your label with size received above.


  UILabel *myLabel=[[UILabel alloc]initWithFrame:a];
  myLabel.text=myString;
  myLabel.font=[UIFont fontWithName:@"Helvetica" size:10];

No comments:

Post a Comment