如何根据标签可用的高度调整UILabel字体大小

时间:2015-08-02 02:28:59

标签: ios swift autolayout

我正在使用自动布局和使用UILables调整文本大小,并且它在宽度方面工作正常,但在高度上却没有那么多。

如果宽度中的文本有空格但文本没有压缩高度

任何想法如何创建约束来做到这一点?或者这是不可能的,我怎样才能找到适合矩形的文本的最小尺寸?

3 个答案:

答案 0 :(得分:7)

您可以将字体设置为自动填充标签的大小,也可以选择不低于最小字体大小。只需将adjustsFontSizeToFitWidth设置为YES即可。如果您需要更多信息,请查看UILabel Class Reference

虽然布尔值被称为“adjustsFontSizeToWidth”,但它实际上意味着标签高度的最大尺寸,它将保留在标签的一行(或者您指定的行数)。

Subclassed UILabel并覆盖layoutSubviews。然后,每次UILabel更改其大小时,都会重新计算字体大小:

var currentuser = PFUser.currentUser().username
var query = PFQuery(className: "_User")
query.whereKey("username", equalTo: currentuser)

query.findObjectsInBackgroundWithBlock {
    (objects: [AnyObject] !, error: NSError ? ) - > Void in
    if error == nil {
        for object in objects {
            self.usernamearray.append(object["username"] as String!)
        }
    }
}
textfield.text = usernamearray // ???? how to do that

答案 1 :(得分:5)

Swift 3.0 对于任何新来的人来说。

非常感谢@tymac的原始答案。

在让我的应用程序变得普遍时,真的帮助我不用担心文字大小。

import UIKit
import Foundation

class LabelWithAdaptiveTextHeight: UILabel {

    override func layoutSubviews() {
        super.layoutSubviews()
        font = fontToFitHeight()
    }

    // Returns an UIFont that fits the new label's height.
    private func fontToFitHeight() -> UIFont {

        var minFontSize: CGFloat = 20
        var maxFontSize: CGFloat = 250
        var fontSizeAverage: CGFloat = 0
        var textAndLabelHeightDiff: CGFloat = 0

        while (minFontSize <= maxFontSize) {
            fontSizeAverage = minFontSize + (maxFontSize - minFontSize) / 2

            if let labelText: String = text {
                let labelHeight = frame.size.height

                let testStringHeight = labelText.size(attributes: [NSFontAttributeName: font.withSize(fontSizeAverage)]).height

                textAndLabelHeightDiff = labelHeight - testStringHeight

                if (fontSizeAverage == minFontSize || fontSizeAverage == maxFontSize) {
                    if (textAndLabelHeightDiff < 0) {
                        return font.withSize(fontSizeAverage - 1)
                    }
                    return font.withSize(fontSizeAverage)
                }

                if (textAndLabelHeightDiff < 0) {
                    maxFontSize = fontSizeAverage - 1

                } else if (textAndLabelHeightDiff > 0) {
                    minFontSize = fontSizeAverage + 1

                } else {
                    return font.withSize(fontSizeAverage)
                }
            }
        }
        return font.withSize(fontSizeAverage)
    }
}

答案 2 :(得分:1)

这是针对所有感兴趣的人的tymac答案的Objective-C实现。

(我有点匆忙,没有时间来修复小写的Gs,Js,Ps和Qs,所以我很快从计算中的平均文本大小中减去了两个功能,对不起。)

#import "LabelWithAdaptiveTextHeight.h"

#define DISPLAY_FONT_MINIMUM 6
#define DISPLAY_FONT_MAXIMUM 50

@interface LabelWithAdaptiveTextHeight ()

@end

@implementation LabelWithAdaptiveTextHeight

- (UIFont*)fontToFitHeight {
    float minimumFontSize = DISPLAY_FONT_MINIMUM;
    float maximumFontSize = DISPLAY_FONT_MAXIMUM;
    float fontSizeAverage = 0;
    float textAndLabelHeightDifference = 0;

    while(minimumFontSize <= maximumFontSize){
        fontSizeAverage = minimumFontSize + (maximumFontSize - minimumFontSize) / 2;
        if(self.text){
            float labelHeight = self.frame.size.height;
            float testStringHeight = [self.text sizeWithAttributes:@{
                                                                NSFontAttributeName: [self.font fontWithSize:fontSizeAverage]
                                                                }].height;

            textAndLabelHeightDifference = labelHeight - testStringHeight;

            if(fontSizeAverage == minimumFontSize || fontSizeAverage == maximumFontSize){
                return [self.font fontWithSize:fontSizeAverage- (textAndLabelHeightDifference < 0)];
            }
            if(textAndLabelHeightDifference < 0){
                maximumFontSize = fontSizeAverage - 1;
            }
            else if(textAndLabelHeightDifference > 0){
                minimumFontSize = fontSizeAverage + 1;
            }
            else{
                return [self.font fontWithSize:fontSizeAverage];
            }
        }
        else {
            break; //Prevent infinite loop
        }
    }
    return [self.font fontWithSize:fontSizeAverage-2];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.font = [self fontToFitHeight];
}

@end