UILabel autoshrink并使用2行,如果有必要

我有一个UILabel,我想先缩小文本,如果可能的话适合单行。 如果这不起作用,我希望最多使用两行。 这可能吗?

目前与设置我有它这样做:

在这里输入图像说明

这是我的布局

在这里输入图像说明在这里输入图像说明

在这里输入图像说明

如果我将行设置更改为1行,文本会缩小。

在这里输入图像说明

我想出了一个解决scheme。

  1. 将“线条”设置为2
  2. 将“换行”设置为“截尾”
  3. 将“自动缩放”设置为“最小字体缩放”,并将该值设置为0.1(或者您希望的最小值)
  4. (可选)选中“拧紧字母间距”

下一部分是在代码中。 我分类UILabel,并提出了这一点。

#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 

然后,当你改变标签的文本时,只需调用autoShrink,它的尺寸就会正确,并且只有在必要的时候才会有两行。

我从这个问题( https://stackoverflow.com/a/11788385/758083 )得到了john.k.doe的大部分代码,