如有必要,UILabel自动收缩并使用2行

时间:2015-06-17 13:40:20

标签: ios objective-c xcode autolayout

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

目前我使用的设置是:

enter image description here

这是我的布局

enter image description here enter image description here

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:3)

我想出了一个解决方案。

  1. Set" Lines"到2
  2. 设置"换行符" to" Truncate Tail"
  3. Set" Autoshrink"到"最小字体比例"并将值设置为0.1(或者您想要的小)
  4. (可选)选中"收紧字母间距"
  5. 下一部分是代码。我将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,它的大小将正确,并且只在必要时才会显示两行。

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

相关问题