0

I might missing something very trivial here, but I can't figure out how to get the width of my UILabel. Note that is it being added programatically, and the it's size fits the text inside it (the text vary from 2 to 35 characters). It automatically fits the right width of it's content, but I need to get the width.

My code to add it to the screen:

    UILabel *textLabel = [[UILabel alloc] init];
    textLabel.text = textInputFromUser;
    textLabel.textColor = [UIColor whiteColor];
    textLabel.backgroundColor = [UIColor colorWithRed:40.0/255.0 green:40.0/255.0 blue:40.0/255.0 alpha:0.95];
    textLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:textLabel];

Note that the following code (with "Bounds"/"Frame") always returns 0.00):

NSLog(@"textlabel width: %f", textLabel.bounds.size.width);
anthoprotic
  • 827
  • 2
  • 13
  • 24

4 Answers4

4

You can only find out the size after the first layout pass. So either wait for that or call

[textLabel layoutIfNeeded];

to layout it immediately. After that the frame should be set to the right value.

felinira
  • 1,644
  • 15
  • 21
0

Since no one else answered, I'll throw in my two cents…

I assume the reason you're unable to get the frame of the label is because the frame hasn't technically been instantiated; but nonetheless, maybe just getting the size of the content would be sufficient for your needs.

Here's a post explaining how to use boundingRectWithSize:options:attributes:context: to get the size of the text in your label: https://stackoverflow.com/a/18961502/2274694

Community
  • 1
  • 1
Lyndsey Scott
  • 37,080
  • 10
  • 92
  • 128
  • I can't it to work. I think I'll just do a calculation based on how many characters are in my UILabel. Not optimal but might work – anthoprotic Dec 15 '13 at 19:36
0

Try initializing the label with a dummy frame like so:

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1,1)];
textLabel.text = textInputFromUser;
[textLabel sizeToFit];

or you could try:

UILabel *textLabel = [[UILabel alloc] initWithString:textInputFromUser];
JustAnotherCoder
  • 2,565
  • 17
  • 38
0

for swift I had to add following code block to get correct width for UILabel:

    private var infoLabel = UILabel()
    infoLabel.translatesAutoresizingMaskIntoConstraints = false
    infoLabel.frame = .zero
    infoLabel.font = UIFont.boldSystemFont(ofSize: 14)
    infoLabel.numberOfLines = -1
    infoLabel.text = "infoText"
    infoLabel.sizeToFit()

to get correct width:

    let infoWidth = infoLabel.frame.size.width

I also added correct constraints to my label (which is infoLabel) according to design given to me.

Burcu Kutluay
  • 472
  • 6
  • 14