Search code examples
iosobjective-cuilabelautolayout

Hot to get UILabel Width using AutoLayout?


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);

Solution

  • 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.