Reputation: 195
I want to auto resize the text size of a UILabel with numberOfLines>1. The UILabel width and height have to be fix. Is there a better solution instead of counting the characters and setting the size manualy? I am using iOS6.
Upvotes: 2
Views: 3358
Reputation: 1328
The below line of code will give you the full size of the string:
CGSize labelSize = [labelString sizeWithFont:label.font constrainedToSize:label.contentSize];
Upvotes: 0
Reputation: 195
I modified a solution I found. This can be used now in a UITableViewCell:
- (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize lblWidth: (float)lblWidth lblHeight: (float)lblHeight {
// use font from provided label so we don't lose color, style, etc
UIFont *font = aLabel.font;
// start with maxSize and keep reducing until it doesn't clip
for(int i = maxSize; i >= minSize; i--) {
font = [font fontWithSize:i];
CGSize constraintSize = CGSizeMake(lblWidth, MAXFLOAT);
// NSString* string = [aLabel.text stringByAppendingString:@"..."];
CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:aLabel.lineBreakMode];
if(labelSize.height <= lblHeight)
break;
}
// Set the UILabel's font to the newly adjusted font.
aLabel.font = font;
}
Upvotes: 4