UILabel autoshrink and use 2 lines if necessary

I have a UILabel that I would like to compress the text first so as possible to go to one line. If this does not work, I would like it to be used in two lines. Is it possible?

Currently with the settings I have this:

enter image description here

Here is my layout

enter image description hereenter image description here

enter image description here

If I change the line setting to 1 line, the text will decrease.

enter image description here

0
ios objective-c xcode autolayout
Jun 17 '15 at 13:40
source share
1 answer

I came up with a solution.

  • Set Lines to 2
  • Set Line Breaks to Truncate Tail
  • Set the Autoshrink parameter to Minimum Font Scale and set it to 0.1 (or how little you would like)
  • (Optional) Check "Tighten spacing"

The next part was in code. I subclassed UILabel and came up with this.

#import <UIKit/UIKit.h> @interface HMFMultiLineAutoShrinkLabel : UILabel - (void)autoShrink; @end 

.

 #import "HMFMultiLineAutoShrinkLabel.h" @interface HMFMultiLineAutoShrinkLabel () @property (readonly, nonatomic) UIFont* originalFont; @end @implementation HMFMultiLineAutoShrinkLabel @synthesize originalFont = _originalFont; - (UIFont*)originalFont { return _originalFont ? _originalFont : (_originalFont = self.font); } - (void)autoShrink { UIFont* font = self.originalFont; CGSize frameSize = self.frame.size; CGFloat testFontSize = _originalFont.pointSize; for (; testFontSize >= self.minimumScaleFactor * self.font.pointSize; testFontSize -= 0.5) { CGSize constraintSize = CGSizeMake(frameSize.width, MAXFLOAT); CGRect testRect = [self.text boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil]; CGSize testFrameSize = testRect.size; // the ratio of testFontSize to original font-size sort of accounts for number of lines if (testFrameSize.height <= frameSize.height * (testFontSize/_originalFont.pointSize)) break; } self.font = font; [self setNeedsLayout]; } @end 

Then, when you change the text of the label, just call autoShrink, and it will have the correct size and will only go two lines if necessary.

I got most of this code from john.k.doe's answer from this question ( stack overflow

+1
Jun 17 '15 at 17:39
source share



All Articles