UILabel自动收缩并在必要时使用2行 [英] UILabel autoshrink and use 2 lines if necessary

查看:66
本文介绍了UILabel自动收缩并在必要时使用2行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UILabel,如果可能的话,我想先缩小文本使其适合一行.如果那行不通,我希望它最多使用两行.这可能吗?

I've got a UILabel that I would like to first shrink the text to fit a single line if possible. If that doesn't work I would like it to use at the most two lines. Is this possible?

目前使用我的设置可以做到这一点:

Currently with the settings I have it does this:

这是我的布局

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

If I change the lines setting to 1 line the text does shrink.

推荐答案

我想出了一个解决方案.

I came up with a solution.

  1. 将行"设置为2
  2. 将换行符"设置为截尾"
  3. 将自动收缩"设置为最小字体比例",并将其值设置为0.1(或者您希望它很小)
  4. (可选)选中收紧字母间距"

下一部分是代码.我将UILabel子类化,并提出了这个方案.

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

然后,无论何时更改标签的文本,只需调用autoShrink即可,它的大小将正确设置,并且仅在必要时才出现两两行.

Then whenver you change the text of the label just call autoShrink and it will be correctly sized and will go two two lines only if necessary.

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

I got most of this code from john.k.doe's answer from this question (https://stackoverflow.com/a/11788385/758083)

这篇关于UILabel自动收缩并在必要时使用2行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆