UILabel trims the tail and skips an inaccurate word

I have one line of UILabel . It has a width = screen width and now the contents (the contents of the UILabel may change)

You have 30 seconds to impress during an interview.

My UILabel is currently truncated tail, and the word "duration" is not complete

 self.nameLabel.lineBreakMode = NSLineBreakByTruncatingTail; 

I want my UILabel still cutting tail and only display the full word.
As picture below

enter image description here

Any help or suggestion would be appreciated.

+5
source share
3 answers

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: we separate the words and check the width when adding from the beginning + the line "...", until we find a word that will exceed the size, in case of stopping and using this new line

+3
source

Ideally this is not possible, with UILabel by default, when you set lineBreakMode to TruncatingTail, depending on the space required by the letter / word that the OS truncates, one solution to fix the problem is that you can use the following properties depending on your match.

Minimal font scale . Use this property to specify the smallest multiplier for the current font size, which gives an acceptable font size for displaying label text. If this property is set to 0, the current font size is used as the smallest font size.

The minimum font size . When drawing text that might not fit into the bounding box of the label, you can use this property to prevent the font size from dropping to the point where it is no longer readable.

0
source

I'm not sure, but I will try:

 nameLabel.adjustsFontSizeToFitWidth = NO; nameLabel.lineBreakMode = NSLineBreakByWordWrapping; 

OR

If you are using a storyboard, follow these steps, I tried this and worked great

  • Open Attribute Inspector
  • Change line breaks to truncate tail, then

  • Change AutoShrink to the minimum font size

enter image description here

here are my screenshots of the label after and before applying these properties

enter image description here

new way out

enter image description here

0
source

All Articles