【问题标题】:UILabel autoshrink and use 2 lines if necessaryUILabel 自动收缩并在必要时使用 2 行
【发布时间】:2015-06-17 13:40:20
【问题描述】:

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

目前我的设置是这样的:

这是我的布局

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

【问题讨论】:

    标签: ios objective-c xcode autolayout


    【解决方案1】:

    我想出了一个解决方案。

    1. 将“线”设置为 2
    2. 将“换行符”设置为“截断尾部”
    3. 将“Autoshrink”设置为“Minimum Font Scale”,并将值设置为 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,它的大小就会正确,并且只有在必要时才会走两两行。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 2013-08-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多