How to adjust font size of a label according to length of string and label size - ios

I have a multi line label with a set size (300 x 300).
I want to adjust the label's font size programmatically according to how long the label's text is and how big the label is.
Here are 2 examples of the same sized labels with different length text strings

Refer to NSString.boundingRectWithSize:options:attributes:. Here you need to decrement the font size stepwise until the string will fit into the original frame.
var paragraph = NSMutableParagraphStyle()
let layout = [NSFontAttributeName:NSFont.systemFontOfSize(0), NSParagraphStyleAttributeName: paragraph, ]
paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
var a = NSString(string: "My long text")
let rect = NSMakeSize(30, 20)
let bb = a.boundingRectWithSize(rect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: layout)
Place the above in Playground and modify rect and the font to see what happens.

I know the Question is old but....
Just use the option AutoShrink and set the minimum font size/scale in the Attributes Inspector, it will scale the font as large as possible to fit the size of the label.

Related

Get truncated text from UILabel in Swift [duplicate]

I have a single line UILabel. It has width = screen width and the content now is (the content of UILabel can change)
You have 30 seconds to make an impression during an interview
Currently, my UILabel is truncated tail and the word "duration" is not complete
self.nameLabel.lineBreakMode = NSLineBreakByTruncatingTail;
What I want is I want my UILabel still truncating tail and only display complete word.
Like the image below
Any help or suggestion would be great appreciated.
You can do something like this:
let labelWidth = CGRectGetWidth(label.bounds)
let str = "You will have 30 seconds till you give us a good impression" as NSString
let words = str.componentsSeparatedByString(" ")
var newStr = "" as NSString
for word in words{
let statement = "\(newStr) \(word) ..." as NSString
let size = statement.sizeWithAttributes([NSFontAttributeName:label.font])
if size.width < labelWidth {
newStr = "\(newStr) \(word)"
}
else{
break
}
}
newStr = newStr.stringByAppendingString(" ...")
self.label.text = newStr as String
Idea is: we split words and try check the width while appending from the beginning + the string "..." till we found the a word that will exceed the size, in the case we stop and use this new string
Ideally this is not possible,with default UILabel, when you set lineBreakMode to TruncatingTail, depending on the space required by the letter/word the OS will truncate it, one solution to fix the issue you can use following properties depending on your match.
Minimum Font Scale -- Use this property to specify the smallest multiplier for the current font size that yields an acceptable font size to use when displaying the label’s text. If you specify a value of 0 for this property, the current font size is used as the smallest font size.
Minimum Font Size -- When drawing text that might not fit within the bounding rectangle of the label, you can use this property to prevent the receiver from reducing the font size to the point where it is no longer legible.
i am not sure but try it:
nameLabel.adjustsFontSizeToFitWidth = NO;
nameLabel.lineBreakMode = NSLineBreakByWordWrapping;
OR
If you are using storyboard follow these steps i tried this and it working fine
Open Attribute Inspector
Change Line Breaks to Truncate Tail then
Change AutoShrink to Minimum Font Size
here are my screenshots of label after and before applying these properties
new output

Find width of string (swift)

How do I find the width of a string (CGFloat) given the font name and font size?
(The goal is to set the width of a UIView to be just wide enough to hold the string.)
I have two strings: one with "1" repeated 36 times, the other with "M" repeated 36 times. These both fill the width (359.0) of the screen (give or take a little for margins).
I am using using Courier 16, which is monospaced, so I expect the width of both strings to be equal (as they in fact do appear on the screen).
However, using https://stackoverflow.com/a/58782429/8635708 :
the width of the string with the "1"s is 257.34375
the width of the string with the "M"s is 492.1875.
The first is does not fill the screen, the other is way too long.
And using https://stackoverflow.com/a/58795998/8635708 :
the width of each string is 249.640625.
At least here, they are the same, but that value clearly does not fill the screen.
I think you could create a label and call label.sizeToFit():
let label = UILabel()
label.font = UIFont.init(name: "Courier", size: 16)
label.text = "mmmmmmmmmmmmmmmm"//"1111111111111111"
label.sizeToFit()
print("Width: \(label.frame.size.width)") //153.66666666666666 -> For both strings

Make UILabel auto-adjust font size to screen width, but not to text length

In a very simple single screen app, I have a single-line UILabel going from left edge to right edge of the screen.
The text of the label is dynamically updated at runtime. The length of the text varies, as it contains a number in the range 0...100, and I am neither using a monospaced font nor leading zeroes.
Here is an illustration:
|<--------- Screen width --------------->|
|<----- UILabel "Some value = 0" ------->|
|<----- UILabel "Some value = 50" ------>|
|<----- UILabel "Some value = 100" ----->|
I would like the label to always use the maximum width for any device (i.e. screen size). This can be achieved by using auto-layout, suitable leading and trailing constraints, a large font size and the "auto-shrink" property for the label.
The problem is, that this approach will make the font size also vary depending on the value displayed, which is not what I want. It should only vary with the width of the screen, but not with the length of the label text.
In the example above, a large font size would be used for the value 0, a medium one for 50 and a small one for 100. I want it to adjust to the worst-case (100) and use the resulting size for any text afterwards.
Is it possible to achieve this using Interface-Builder properties and auto-layout constraints only?
I can think of ways how to calculate sizes in code, but I think there must be an easier way.
You cannot express font size as a proportion of view width in interface builder but you can do it very easily in code:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let textSize = Constant.baseFontSize * bounds.size.width / Constant.baseViewWidth
label.font = .systemFont(ofSize: textSize)
}

convert sketch line height into ios line 'height multiple' property

My designer send me sketch file which says 'Line height: 22' for label. How can i achieve this in xcode interface builder.
Is there any way to define this line height using code or UI builder.
#bbjay did put me on the right track.
If you want to obtain the exact result of Sketch, the formula is:
paragraphStyle .lineSpacing = sketchLineHeight - font.lineHeight
Provided that the font was given sketchFontSize
I've found the following formula to work well for me.
It converts form Sketch line height to iOS line spacing:
lineSpacing = sketchLineHeight - sketchFontSize - (font.lineHeight - font.pointSize)
In code, for your case this would be:
let font = UIFont.systemFont(ofSize: 18) // or whatever font you use
textLabel.font = font
let attributedString = NSMutableAttributedString(string: "your text")
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 22 - 18 - (font.lineHeight - font.pointSize)
attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
textLabel.attributedText = attributedString
Line height is coming from CSS, so your designer must have a web designer background. On the mobile platforms, we do not specify line height, but line spacing.
In general NSMutableParagraphStyle offers capabilities to modify multiline labels for iOS.
NSMutableParagraphStyle has a property called maximumLineHeight, but this will only set the maximum line height to a certain value, if the containment of the label would exceed a certain value.
To set this up in IB, you need to add the label, and change the Text property to Attributed. Than click on paragraph style icon, and set the line spacing for the label. Looking at the design, it is around 2 points of line spacing, what you need. You can either ask your designer to provide you with line spacing attribute or try to find the right line spacing value by randomly trying out different values.
In storyboard, use the Atributed style of UILabel. Below is example with 2.5 line height

UILabel truncate tail and skip not complete word

I have a single line UILabel. It has width = screen width and the content now is (the content of UILabel can change)
You have 30 seconds to make an impression during an interview
Currently, my UILabel is truncated tail and the word "duration" is not complete
self.nameLabel.lineBreakMode = NSLineBreakByTruncatingTail;
What I want is I want my UILabel still truncating tail and only display complete word.
Like the image below
Any help or suggestion would be great appreciated.
You can do something like this:
let labelWidth = CGRectGetWidth(label.bounds)
let str = "You will have 30 seconds till you give us a good impression" as NSString
let words = str.componentsSeparatedByString(" ")
var newStr = "" as NSString
for word in words{
let statement = "\(newStr) \(word) ..." as NSString
let size = statement.sizeWithAttributes([NSFontAttributeName:label.font])
if size.width < labelWidth {
newStr = "\(newStr) \(word)"
}
else{
break
}
}
newStr = newStr.stringByAppendingString(" ...")
self.label.text = newStr as String
Idea is: we split words and try check the width while appending from the beginning + the string "..." till we found the a word that will exceed the size, in the case we stop and use this new string
Ideally this is not possible,with default UILabel, when you set lineBreakMode to TruncatingTail, depending on the space required by the letter/word the OS will truncate it, one solution to fix the issue you can use following properties depending on your match.
Minimum Font Scale -- Use this property to specify the smallest multiplier for the current font size that yields an acceptable font size to use when displaying the label’s text. If you specify a value of 0 for this property, the current font size is used as the smallest font size.
Minimum Font Size -- When drawing text that might not fit within the bounding rectangle of the label, you can use this property to prevent the receiver from reducing the font size to the point where it is no longer legible.
i am not sure but try it:
nameLabel.adjustsFontSizeToFitWidth = NO;
nameLabel.lineBreakMode = NSLineBreakByWordWrapping;
OR
If you are using storyboard follow these steps i tried this and it working fine
Open Attribute Inspector
Change Line Breaks to Truncate Tail then
Change AutoShrink to Minimum Font Size
here are my screenshots of label after and before applying these properties
new output

Resources