Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align the attributed text within a UILabel

When set the attributed text of a UILabel and use the setFontSizeToFitWidth the attributed text font size resizes as expected. BUT.. The text is not vertically aligned inside the UILabel when the attributed string font size resizes to a smaller font size.

I need to use the method adjustFontSizeToFitWidth because the attributed string has a variable size. I have the minimum font size set to "15.0" and the maximum to "28.0". Therefore I use the minimumScaleFactor of "15.0/28.0"

My Code:

NSAttributedString *balance = [[NSAttributedString alloc] initWithString:@"12390765298374652938756" attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];

// Create UILabel with a 10.0 point padding around the UILabel within the parent Rect
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.bounds.origin.x + 10, self.bounds.origin.y + 10, self.bounds.size.width - 20, self.bounds.size.height - 20)];

textLabel.attributedText = currencyWithBalance;
textLabel.font = [UIFont fontWithName:@"TitilliumWeb-Light" size:28.0];
textLabel.minimumScaleFactor = 15.0/28.0;
textLabel.textAlignment = NSTextAlignmentCenter;
textLabel.adjustsFontSizeToFitWidth = YES;
textLabel.numberOfLines = 1;
textLabel.backgroundColor = [UIColor redColor];


[self addSubview:textLabel];

Can anyone help me to achieve this, so that the text is also vertically aligned?

Thanks guys.

like image 767
michel Avatar asked Nov 10 '22 09:11

michel


1 Answers

First, use sizeToFit as pointed out by XCodian's comment. That'll ensure that the label's adjusts itself to the current text size.

Next, you need to position the label's frame vertically in its container (in your example that's self). To accomplish that, you add a constraint for that, using [UIView addConstraint:].

Something like this should be added to the end of your code to make this work, probably:

[self addConstraint:
  [NSLayoutConstraint constraintWithItem:textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]
];
like image 184
Thomas Tempelmann Avatar answered Nov 15 '22 05:11

Thomas Tempelmann