birdcage
birdcage

Reputation: 2676

Creating UILabel programmatically with dynamic size

I am trying to create UILabel programmatically, but height and width should be set dynamically depending on the content. I don't want to create initial CGRect with some width and height, which cause design issues in my case.

What I tried to do is:

        self.freeLabel = [[UILabel alloc] initWithFrame:CGRectMake(frameView.layer.frame.size.width - 50, -8, 120, 25)];
        self.freeLabel.numberOfLines = 0;
        [self.freeLabel setBackgroundColor:[UIColor colorWithRed:0.91 green:0.18 blue:0.42 alpha:1.0]];
        self.freeLabel.layer.cornerRadius = 5;
        self.freeLabel.layer.masksToBounds = YES;
        [self addSubview:self.freeLabel];
        [self sizeToFit];

but this way I cannot add the UILabel to my view.

Upvotes: 1

Views: 155

Answers (1)

Fahim Parkar
Fahim Parkar

Reputation: 31647

you have to add below codes so that self.freeLabel with take new height.

[self.freeLabel sizeToFit];

self.freeLabel.frame = CGRectMake(frameView.layer.frame.size.width - 50, -8, 120, self.freeLabel.frame.size.height)];

self.frame = // update size based on the height of the label.

But I have some points which I feel are wrong.

Why x position of self.freeLabel is defined as frameView.layer.frame.size.width - 50 but width of label as 120. For sure this label will go out of your view. So frameView.layer.frame.size.width - 50 should be frameView.layer.frame.size.width - 120

Upvotes: 1

Related Questions