Reputation: 8651
I have a UILabel with a font of point size 17. If I call label.font.pointSize I get 17, which is all good. BBUUUUTTT I also have a minimumfontsize set to 8, now if I cram some text in the label which causes the point size to shrink and then call label.font.pointsize I still get 17 even though I know the point size is smaller
Any ideas how to get the true point size after system has resized the font?
Upvotes: 7
Views: 3500
Reputation: 1450
Swift 4 and iOS 7+ version (sizeWithFont
is now deprecated) of @Sanjit Saluja's answer:
// Get the size of the text with no scaling (one line)
let sizeOneLine: CGSize = label.text!.size(withAttributes: [NSAttributedStringKey.font: label.font])
// Get the size of the text enforcing the scaling based on label width
let sizeOneLineConstrained: CGSize = label.text!.boundingRect(with: label.frame.size, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: label.font], context: nil).size
// Approximate scaling factor
let approxScaleFactor: CGFloat = sizeOneLineConstrained.width / sizeOneLine.width
// Approximate new point size
let approxScaledPointSize: CGFloat = approxScaleFactor * label.font.pointSize
Upvotes: 1
Reputation: 8651
As savner pointed out in the comments, this is a duplication question. The cleanest solution is found here: How to get UILabel (UITextView) auto adjusted font size?. However, Sanjit's solution also works! Thanks Everybody!
CGFloat actualFontSize;
[label.text sizeWithFont:label.font
minFontSize:label.minimumFontSize
actualFontSize:&actualFontSize
forWidth:label.bounds.size.width
lineBreakMode:label.lineBreakMode];
Upvotes: 2
Reputation: 7287
I don't know of an API to get the current point size of the UILabel when it is scaling your content down. You can try to approximate "scaling factor" using sizeWithFont
APIs.
Just an idea:
// Get the size of the text with no scaling (one line)
CGSize sizeOneLine = [label.text sizeWithFont:label.font];
// Get the size of the text enforcing the scaling based on label width
CGSize sizeOneLineConstrained = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size];
// Approximate scaling factor
CGFloat approxScaleFactor = sizeOneLineConstrained.width / sizeOneLine.width;
// Approximate new point size
CGFloat approxScaledPointSize = approxScaleFactor * label.font.pointSize;
Upvotes: 4