如何调整标签的字体大小以适应矩形?

don*_*ile 36 iphone uilabel

是的,这是一个很酷的myLabel.adjustsFontSizeToFitWidth = YES;财产.但是只要标签有两行或更多行,它就不会将文本大小调整为任何内容.因此它只会被截断...如果它不适合矩形.

还有另一种方法吗?

Nie*_*tle 49

如果你想确保标签适合宽度和高度的矩形,你可以在标签上尝试不同的字体大小,看看是否适合.

此片段以300 pt开始,并尝试通过减小字体大小使标签适合目标矩形.

- (void) sizeLabel: (UILabel *) label toRect: (CGRect) labelRect {

    // Set the frame of the label to the targeted rectangle
    label.frame = labelRect;

    // Try all font sizes from largest to smallest font size
    int fontSize = 300;
    int minFontSize = 5;

    // Fit label width wize
    CGSize constraintSize = CGSizeMake(label.frame.size.width, MAXFLOAT);

    do {
        // Set current font size
        label.font = [UIFont fontWithName:label.font.fontName size:fontSize];

        // Find label size for current font size
        CGRect textRect = [[label text] boundingRectWithSize:constraintSize
                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                  attributes:@{NSFontAttributeName: label.font}
                                                     context:nil];

        CGSize labelSize = textRect.size;

        // Done, if created label is within target size
        if( labelSize.height <= label.frame.size.height )
            break;

        // Decrease the font size and try again
        fontSize -= 2;

    } while (fontSize > minFontSize);
}
Run Code Online (Sandbox Code Playgroud)

我认为上面解释了发生了什么.更快的实现可以使用缓存和argarcians二进制搜索,如下所示

+ (CGFloat) fontSizeForString: (NSString*) s inRect: (CGRect) labelRect  {
    // Cache repeat queries
    static NSMutableDictionary* mutableDict = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mutableDict = [NSMutableDictionary dictionary];
    });

    NSString* key = [NSString stringWithFormat:@"%@_%d_%d", s, (int) labelRect.size.width, (int) labelRect.size.height];
    NSNumber* value = [mutableDict objectForKey:key];
    if (value)
        return value.doubleValue;

    // Set the frame of the label to the targeted rectangle
    UILabel* label = [[UILabel alloc] init];
    label.text = s;
    label.frame = labelRect;

    // Hopefully between 5 and 300
    CGFloat theSize = (CGFloat) [self binarySearchForFontSizeForLabel:label withMinFontSize:5 withMaxFontSize:300 withSize:label.frame.size];
    [mutableDict setObject:@(theSize) forKey:key];
    return  theSize;
}


+ (NSInteger)binarySearchForFontSizeForLabel:(UILabel *)label withMinFontSize:(NSInteger)minFontSize withMaxFontSize:(NSInteger)maxFontSize withSize:(CGSize)size {
    // If the sizes are incorrect, return 0, or error, or an assertion.
    if (maxFontSize < minFontSize) {
        return maxFontSize;
    }

    // Find the middle
    NSInteger fontSize = (minFontSize + maxFontSize) / 2;
    // Create the font
    UIFont *font = [UIFont fontWithName:label.font.fontName size:fontSize];
    // Create a constraint size with max height
    CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);
    // Find label size for current font size
    CGRect rect = [label.text boundingRectWithSize:constraintSize
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:@{NSFontAttributeName : font}
                                           context:nil];
    CGSize labelSize = rect.size;

    // EDIT:  The next block is modified from the original answer posted in SO to consider the width in the decision. This works much better for certain labels that are too thin and were giving bad results.
    if (labelSize.height >= (size.height + 10) && labelSize.width >= (size.width + 10) && labelSize.height <= (size.height) && labelSize.width <= (size.width)) {
        return fontSize;
    } else if (labelSize.height > size.height || labelSize.width > size.width) {
        return [self binarySearchForFontSizeForLabel:label withMinFontSize:minFontSize withMaxFontSize:fontSize - 1 withSize:size];
    } else {
        return [self binarySearchForFontSizeForLabel:label withMinFontSize:fontSize + 1 withMaxFontSize:maxFontSize withSize:size];
    }
}
Run Code Online (Sandbox Code Playgroud)


aga*_*ian 31

我发现Niels的回答是这个问题的最佳答案.但是,我有一个UIView,它可以有100个标签,我需要适合文本,所以这个过程非常低效,我可以感受到性能的打击.

这是他的代码修改为使用二进制搜索而不是线性搜索.现在它非常有效.

- (NSInteger)binarySearchForFontSizeForLabel:(UILabel *)label withMinFontSize:(NSInteger)minFontSize withMaxFontSize:(NSInteger)maxFontSize withSize:(CGSize)size {
    // If the sizes are incorrect, return 0, or error, or an assertion.
    if (maxFontSize < minFontSize) {
        return 0;
    }

    // Find the middle
    NSInteger fontSize = (minFontSize + maxFontSize) / 2;
    // Create the font
    UIFont *font = [UIFont fontWithName:label.font.fontName size:fontSize];
    // Create a constraint size with max height
    CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);
    // Find label size for current font size
    CGRect rect = [label.text boundingRectWithSize:constraintSize
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:@{NSFontAttributeName : font}
                                           context:nil];
    CGSize labelSize = rect.size;

    // EDIT:  The next block is modified from the original answer posted in SO to consider the width in the decision. This works much better for certain labels that are too thin and were giving bad results.
    if (labelSize.height >= (size.height + 10) && labelSize.width >= (size.width + 10) && labelSize.height <= (size.height) && labelSize.width <= (size.width)) {
        return fontSize;
    } else if (labelSize.height > size.height || labelSize.width > size.width) {
        return [self binarySearchForFontSizeForLabel:label withMinFontSize:minFontSize withMaxFontSize:fontSize - 1 withSize:size];
    } else {
        return [self binarySearchForFontSizeForLabel:label withMinFontSize:fontSize + 1 withMaxFontSize:maxFontSize withSize:size];
    }
}

- (void)sizeBinaryLabel:(UILabel *)label toRect:(CGRect)labelRect {

    // Set the frame of the label to the targeted rectangle
    label.frame = labelRect;

    // Try all font sizes from largest to smallest font
    int maxFontSize = 300;
    int minFontSize = 5;

    NSInteger size = [self binarySearchForFontSizeForLabel:label withMinFontSize:minFontSize withMaxFontSize:maxFontSize withSize:label.frame.size];

    label.font = [UIFont fontWithName:label.font.fontName size:size];

}
Run Code Online (Sandbox Code Playgroud)

可以获得https://gist.github.com/988219

  • 嗯,@ agarcian的代码总是给我0.maxFontSize和minFontSize在没有第一个if-then的情况下变得相等.即使在一个非常基础的测试项目中.Niels的代码运行良好,尽管速度较慢. (6认同)
  • 谢谢帕万.这就是SO的美.协作将为我们节省数小时的开发时间:-) (2认同)

nRe*_*wik 8

根据@NielsCastle的回答,使用二进制搜索,这是Swift版本

extension UILabel{

    func adjustFontSizeToFitRect(rect : CGRect){

        if text == nil{
            return
        }

        frame = rect

        let maxFontSize: CGFloat = 100.0
        let minFontSize: CGFloat = 5.0

        var q = Int(maxFontSize)
        var p = Int(minFontSize)

        let constraintSize = CGSize(width: rect.width, height: CGFloat.max)

        while(p <= q){
            let currentSize = (p + q) / 2
            font = font.fontWithSize( CGFloat(currentSize) )
            let text = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:font])
            let textRect = text.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, context: nil)

            let labelSize = textRect.size

            if labelSize.height < frame.height && labelSize.height >= frame.height-10 && labelSize.width < frame.width && labelSize.width >= frame.width-10 {
                break
            }else if labelSize.height > frame.height || labelSize.width > frame.width{
                q = currentSize - 1
            }else{
                p = currentSize + 1
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

用法

label.adjustFontSizeToFitRect(rect)
Run Code Online (Sandbox Code Playgroud)

经常只是

label.adjustFontSizeToFitRect(rect.frame)
Run Code Online (Sandbox Code Playgroud)


Fer*_*nch 5

此解决方案(基于此答案)适用于自动布局并执行二进制搜索以查找最佳字体大小.

我发现的唯一警告是你不能指定行数(因为AFAIK你不知道boundingRectWithSize你想要多少行).

AdjustableLabel.h

#import <UIKit/UIKit.h>

@interface AdjustableLabel : UILabel
/** 
  If set to YES, font size will be automatically adjusted to frame.
  Note: numberOfLines can't be specified so it will be set to 0.
*/
@property(nonatomic) BOOL adjustsFontSizeToFitFrame;
@end
Run Code Online (Sandbox Code Playgroud)

AdjustableLabel.m

#import "AdjustableLabel.h"

@interface AdjustableLabel ()
@property(nonatomic) BOOL fontSizeAdjusted;
@end

// The size found S satisfies: S fits in the frame and and S+DELTA doesn't.
#define DELTA 0.5

@implementation AdjustableLabel

- (void)setAdjustsFontSizeToFitFrame:(BOOL)adjustsFontSizeToFitFrame
{
    _adjustsFontSizeToFitFrame = adjustsFontSizeToFitFrame;

    if (adjustsFontSizeToFitFrame) {
        self.numberOfLines = 0; // because boundingRectWithSize works like this was 0 anyway
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (self.adjustsFontSizeToFitFrame && !self.fontSizeAdjusted)
    {
        self.fontSizeAdjusted = YES; // to avoid recursion, because adjustFontSizeToFrame will trigger this method again

        [self adjustFontSizeToFrame];
    }
}

- (void) adjustFontSizeToFrame
{
    UILabel* label = self;

    if (label.text.length == 0) return;

    // Necessary or single-char texts won't be correctly adjusted
    BOOL checkWidth = label.text.length == 1;

    CGSize labelSize = label.frame.size;

    // Fit label width-wise
    CGSize constraintSize = CGSizeMake(checkWidth ? MAXFLOAT : labelSize.width, MAXFLOAT);

    // Try all font sizes from largest to smallest font size
    CGFloat maxFontSize = 300;
    CGFloat minFontSize = 5;

    NSString* text = label.text;
    UIFont* font = label.font;

    while (true)
    {
        // Binary search between min and max
        CGFloat fontSize = (maxFontSize + minFontSize) / 2;

        // Exit if approached minFontSize enough
        if (fontSize - minFontSize < DELTA/2) {
            font = [UIFont fontWithName:font.fontName size:minFontSize];
            break; // Exit because we reached the biggest font size that fits
        } else {
            font = [UIFont fontWithName:font.fontName size:fontSize];
        }

        // Find label size for current font size
        CGRect rect = [text boundingRectWithSize:constraintSize
                                         options:NSStringDrawingUsesLineFragmentOrigin
                                      attributes:@{NSFontAttributeName : font}
                                         context:nil];

        // Now we discard a half
        if( rect.size.height <= labelSize.height && (!checkWidth || rect.size.width <= labelSize.width) ) {
            minFontSize = fontSize; // the best size is in the bigger half
        } else {
            maxFontSize = fontSize; // the best size is in the smaller half
        }
    }

    label.font = font;
}

@end
Run Code Online (Sandbox Code Playgroud)

用法

AdjustableLabel* label = [[AdjustableLabel alloc] init];
label.adjustsFontSizeToFitFrame = YES;

// In case you change the font, the size you set doesn't matter
label.font = [UIFont fontWithName:@"OpenSans-Light" size:20];
Run Code Online (Sandbox Code Playgroud)


小智 5

这是 UILabel 的 Swift 扩展。它运行二进制搜索算法来调整标签的字体和边界大小,并经过测试适用于 iOS 12。

用法:调整字体大小以适应 100x100 的大小(精确到 1.0 字体点内)并将其与顶部对齐。

let adjustedSize = <label>.fitFontForSize(CGSizeMake(100, 100))
<label>.frame = CGRect(x: 0, y: 0, width: 100, height: adjustedSize.height)
Run Code Online (Sandbox Code Playgroud)

将以下内容复制/粘贴到您的文件中:

extension UILabel {
    @discardableResult func fitFontForSize(_ constrainedSize: CGSize,
                                           maxFontSize: CGFloat = 100,
                                           minFontSize: CGFloat = 5,
                                           accuracy: CGFloat = 1) -> CGSize {
        assert(maxFontSize > minFontSize)

        var minFontSize = minFontSize
        var maxFontSize = maxFontSize
        var fittingSize = constrainedSize

        while maxFontSize - minFontSize > accuracy {
            let midFontSize: CGFloat = ((minFontSize + maxFontSize) / 2)
            font = font.withSize(midFontSize)
            fittingSize = sizeThatFits(constrainedSize)
            if fittingSize.height <= constrainedSize.height
                && fittingSize.width <= constrainedSize.width {
                minFontSize = midFontSize
            } else {
                maxFontSize = midFontSize
            }
        }

        return fittingSize
    }
} 
Run Code Online (Sandbox Code Playgroud)

该函数不会改变标签大小,只会font影响属性。您可以使用返回的大小值来调整标签的布局。