Search code examples
iosuilabelnsattributedstring

Calculate the minimum rectangle around text in UIlabel


I programmatically create some text.
The text gets attributes and then returns to the view controller where is displayed.
Originally i create a rectangle UIlabel with max height 40.
Therefore if the the text is too big the font size decreases to fit into the rectangle by
applying to the text adjustsFontSizeToFitWidth.
If the text is small there is a lot of empty space in the rectangle (on top and below).
Is it possible at that point to get the minimum rectangle eclosing my text.
Thank you

.

NSAttributedString * Text=[circleModel.Selected_set objectForKey:@"sentence_text"];
CGRect recty;
recty= CGRectMake(mainScreen.size.width*0.55, 100, mainScreen.size.width*0.43,40);

UILabel *Latex_text = [[UILabel alloc] initWithFrame:recty];
Latex_text.AttributedText = Text;
Latex_text.numberOfLines = 0;

Latex_text.adjustsFontSizeToFitWidth = YES;
Latex_text.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:Latex_text];
//Latex_text.backgroundColor = [UIColor whiteColor];

Solution

  • What about using textRectForBounds? It should give you at least an estimate if the adjustsFontSizeToFitWidth doesn't play well with it.

    UILabel *Latex_text = [[UILabel alloc] init];
    Latex_text.AttributedText = Text;
    Latex_text.numberOfLines = 0;
    
    Latex_text.adjustsFontSizeToFitWidth = YES;
    Latex_text.textAlignment = NSTextAlignmentCenter;
    recty.size = [Latex_text textRectForBounds:recty limitedToNumberOfLines:0].size;
    [Latex_text setFrame:recty];