azamsharp
azamsharp

Reputation: 20094

Dynamically Creating and Positioning UILabels of Different Sizes

I am creating dynamic UILabels and then adding them to the view. The labels are in vertical layout. Like this:

Label 1

Label 2

Label 3

Each label can be of different height. So in order to accomodate the height I use the following code. The Label 2 uses Label 1 position and height to adjust itself on the view.

    -(void) createAboutLabel 
{
    self.aboutLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.nameLabel.frame.origin.x, self.nameLabel.frame.origin.y + self.nameLabel.frame.size.height, self.view.frame.size.width - 10, 40)];

    self.aboutLabel.text = self.selectedVegetableCategory.about;
    self.aboutLabel.font = [Utility getFont:@"Sinhala Sangam MN" size:14];
 //   [self.aboutLabel sizeToFit];
    [self.aboutLabel setNumberOfLines:0];
    [self.aboutLabel setLineBreakMode:UILineBreakModeWordWrap];
    [self.aboutLabel sizeToFit];
    [self.scrollView addSubview:self.aboutLabel];
}

I am trying to find a better way of achieving the dynamic label layout.

Any suggestions?

Upvotes: 0

Views: 1672

Answers (1)

PawanShakya
PawanShakya

Reputation: 97

By passing width & font, height can be retrieved -

NSString *theText = myLabel.text; CGFloat width = myLabel.frame.size.width ; CGSize theSize = [theText sizeWithFont:myLabel.font constrainedToSize:CGSize(width,MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];

It will return the size from that extract height. CGFloat myLabelHeight = theSize.height;

Hope this should help.

Upvotes: 1

Related Questions