Search code examples
iphoneiosuilabelsizetofit

why is the "sizeToFit" call required in this code?


Anyone able to highlight why the "[aLabel sizeToFit]" line is required in this code below, taken from here.

That is, the CGRect created has already been sized based on the text font size, so why would the sizeToFit be required? Or is it because whilst they calculated the correct CGRect size they actually didn't set the pre-agreed font (system font) to the UILabel yet? (and therefore effectively called sizeToFit instead of setting the font)

- (CGRect)RAD_frameForCellLabelWithSystemFontOfSize:(CGFloat)size {
    CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
    CGFloat height = [self RAD_textHeightForSystemFontOfSize:size] + 10.0;
    return CGRectMake(10.0f, 10.0f, width, height);
}

- (void)RAD_resizeLabel:(UILabel *)aLabel WithSystemFontOfSize:(CGFloat)size {
    aLabel.frame = [self RAD_frameForCellLabelWithSystemFontOfSize:size];
    aLabel.text = self;
    [aLabel sizeToFit];    // WHY IS THIS REQUIRED
}

Solution

  • From docs:

    Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs. In some cases, if a view does not have a superview, it may size itself to the screen bounds. Thus, if you want a given view to size itself to its parent view, you should add it to the parent view before calling this method.

    Choose the right one, that is appropriate for your case.