0

I want to set the width of the uilabel based on the text length and then on top of that make it a little bit wider. The text might be different so I cannot just predefine the width of the uilabel. My approach to this is to get the width of the text and then add another 10.0 to it but it doesn't work.

CGSize tSize = [[self.label1 text] sizeWithAttributes:@{NSFontAttributeName:[self.label1 font]}];
CGFloat tWidth = tSize.width + 10.0;
self.label1.frame = CGRectMake(self.label1.frame.origin.x, self.label1.frame.origin.y, tWidth, self.label1.frame.size.height);
self.label1.backgroundColor = [UIColor blueColor];

Any advice is much appreciated.

bubibu
  • 324
  • 1
  • 4
  • 12
  • Emm, you might want to share with us how exactly "it doesn't work". One question: are you using autolayout by any chance? – Rok Jarc Nov 19 '16 at 18:14
  • 1
    If your problem is to add padding, take a look at here: http://stackoverflow.com/questions/3476646/uilabel-text-margin If the width is not calculated correctly at all, I suggest you to use auto layout, if you don't want, as @RokJarc suggested, elaborate how it doesn't work. – EDUsta Nov 19 '16 at 19:17
  • Yes I am using autolayout, everything works fine but I don't want the width of the uilabel to fit exactly, I want it to be slightly wider than the text. – bubibu Nov 22 '16 at 04:00

1 Answers1

1

You might want to use [yourLabel sizeToFit]; or [yourLabel sizeThatFits: <#your target size#>];

sizeToFit resizes your label within it's current frame.size according to it's current text , font and the numberOfLines you provided.

Then you can change the size

[yourLabel sizeToFit];
CGRect rect = yourLabel.frame;
rect.size.width += 10;
yourLabel.frame = rect;

sizeThatFits:(CGSize)size doesn't resize your label but it returns the size that fits the size you pass as parameter. sizeToFit uses sizeThatFits:(CGSize)size internally.

You can change size by doing this

CGSize exampleSize = (CGSize){300, 300};
CGSize fittingSize = [yourLabel sizeThatFits: exampleSize];
CGRect rect = yourLabel.frame;
rect.size.width = fittingSize.width;
rect.size.height = fittingSize.height;
yourLabel.frame = rect;

This should be working fine even if you are working with yourLabel.attributedText

Cosmos Man
  • 593
  • 3
  • 15
  • @bubibu if you want label with padding like in HTML, you need to set your label's text alignment to `NSTextAlignmentCenter`; – Cosmos Man Nov 20 '16 at 06:27