Reputation: 3014
I have several UILables
in my view like this:
Those in red colour should never change their font size. Two others in white colour (50 and 50) should decrease their font size proportionally to fit the content. What I want to achieve is when any of white labels becomes two big the other should start decreasing in size as well:
but instead I get this:
How can I make my UILabels' font size to resize proportionally?
Upvotes: 3
Views: 1114
Reputation: 16543
I expected the answer to this is in NSMutableAttributedString
so i did a small experiment with this
NSString *quantity = @"123456";
NSString *metrics =@"m2";
NSString *quantity2 = @"50";
NSString *metrics2 =@"pk";
NSString *separator = @" / ";
NSMutableAttributedString *fullString = [[NSMutableAttributedString alloc] initWithString:
[NSString stringWithFormat:@"%@%@%@%@%@",quantity,metrics,separator,quantity2,metrics2]];
[fullString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:25.0]
range:NSMakeRange(quantity.length+metrics.length, separator.length)];
[fullString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:12.0]
range:NSMakeRange(fullString.length-metrics.length, metrics.length)];
_lblTitle.attributedText = fullString;
So try changing the values and adding attributes you will get what you want
Upvotes: 1
Reputation: 17186
The easiest possible way is as below:
Upvotes: 1
Reputation: 2842
One easy way to do this is by adjusting the fontSize manually using UILabel's
sizeToFit
method to calculate its bounds.
int fontSize = MAX_FONTSIZE;
BOOL fontSizeNeedsToBeAdjusted = NO;
CGRect originalLabelFrame1 = label1.frame;
CGRect originalLabelFrame2 = label2.frame;
while(fontSizeNeedsToBeAdjusted && fontSize>MIN_FONTSIZE){
label1.frame = originalLabelFrame1;
label1.font = [UIFont systemFontOfSize:fontSize];
[label1 sizeToFit];
label2.frame = originalLabelFrame2;
label2.font = [UIFont systemFontOfSize:fontSize];
[label2 sizeToFit];
if(CGRectGetWidth(label1.frame)>CGRectGetWidth(originalLaeblFrame1) || CGRectGetHeight(label1.frame)>CGRectGetHeight(originalLaeblFrame1))
|| CGRectGetWidth(label2.frame)>CGRectGetWidth(originalLaeblFrame2) || CGRectGetHeight(label2.frame)>CGRectGetHeight(originalLaeblFrame2)){
fontSizeNeedsToBeAdjusted = YES;
fontSize--;
}else
fontSizeNeedsToBeAdjusted = NO;
}
A quicker way would be calculating the size with NSString's
boundingRectWithSize: options:attributes:context:
method:
NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontofSize:fontSize]};
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
CGRect bounds = [label1.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(label1.frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
Upvotes: 1