Ashish Agarwal
Ashish Agarwal

Reputation: 14925

Dynamically Sizing UILabels

In my app I have 4 labels and I need to add them immediately below the previous label. The problem is that these labels are filled with text dynamically and I don't know the size of the label.

For example, in the code below I have 2 labels - myLabel and titleLabel. I need to paste the titleLabel immediately below myLabel, but the problem is that the height of the latter varies. And so I am not able to give the y-coordinate of titleLabel.

CGRect labelFrame = CGRectMake(22, 50, 280, 150);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
[myLabel setText:finalIngredients];
[myLabel setBackgroundColor: [UIColor lightGrayColor]];
[myLabel setFont:[UIFont fontWithName:@"Helvetica" size:15]];
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
[self.view addSubview:myLabel];


CGRect titleLabelFrame = CGRectMake(0, 25, 400, 15);
UILabel *titleLabel = [[UILabel alloc] initWithFrame:titleLabelFrame];
[titleLabel setText:title];
[self.view addSubview:titleLabel];

Thanks

Upvotes: 0

Views: 2376

Answers (3)

niklon
niklon

Reputation: 176

Make use of myLabel.bounds.size.height and myLabel.frame.origin.y to get height and starting y-coordinate for myLabel, respectively. To my knowledge they will change dynamically when you invoke sizeToFit (for instance). In your case you could simply change the line

CGRect titleLabelFrame = CGRectMake(0, 25, 400, 15);

to

CGRect titleLabelFrame = CGRectMake(0, myLabel.frame.origin.y + myLabel.bounds.size.height, 400, 15);

Upvotes: 2

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

Calulate height dynamiclly with this:

 CGSize size = [finalIngredients sizeWithFont:[UIFont systemFontOfSize:15]
      constrainedToSize:CGSizeMake(100, 200)
          lineBreakMode:UILineBreakModeWordWrap];

Here finalIngredients is your string. You just have to provide width of your label u want in place of 100.

Make calulation of label's frame dynamically depending on previous or next label

Upvotes: 1

WendiKidd
WendiKidd

Reputation: 4373

If the text is dynamic, it stands to reason you have a function that modifies the text.

Inside that function, calculate the height of the newly modified text inside myLabel. Then set the y position of titleLabel to be myLabel's x position + myLabel's newly calculated height + whatever buffer space you require between them. :)

Upvotes: 0

Related Questions