web-dev-qa-db-ja.com

UILabelのフォントサイズを動的に変更する

私は現在UILabelを持っています:

factLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 280, 100)];
factLabel.text = @"some text some text some text some text";
factLabel.backgroundColor = [UIColor clearColor];
factLabel.lineBreakMode = UILineBreakModeWordWrap;
factLabel.numberOfLines = 10;
[self.view addSubview:factLabel];

私のiOSアプリケーションの寿命を通して、factLabelはたくさんの異なる値を取得します。複数の文を含むものもあれば、5〜6語しかないものもあります。

テキストが常に定義した範囲内に収まるようにフォントサイズが変わるようにUILabelを設定するにはどうすればよいですか。

178
CodeGuy

単一行:

factLabel.numberOfLines = 1;
factLabel.minimumFontSize = 8;
factLabel.adjustsFontSizeToFitWidth = YES;

上記のコードはあなたのテキストのフォントサイズを(例えば)ラベルに収まるように(例えば)8に調整します。 numberOfLines = 1は必須です。

複数行:

numberOfLines > 1には NSStringのsizeWithFont:... UIKit追加 メソッドを通して最終的なテキストのサイズを計算するメソッドがあります、例えば:

CGSize lLabelSize = [yourText sizeWithFont:factLabel.font
                                  forWidth:factLabel.frame.size.width
                             lineBreakMode:factLabel.lineBreakMode];

その後は、結果のlLabelSizeを使用してラベルのサイズを変更できます(ラベルの高さのみを変更すると仮定します)。

factLabel.frame = CGRectMake(factLabel.frame.Origin.x, factLabel.frame.Origin.y, factLabel.frame.size.width, lLabelSize.height);

iOS6

単一行:

IOS6以降、minimumFontSizeは非推奨になりました。この線

factLabel.minimumFontSize = 8.;

に変更することができます。

factLabel.minimumScaleFactor = 8./factLabel.font.pointSize;

iOS7

複数行:

IOS7以降、sizeWithFontは非推奨になりました。複数行の場合は次のようになります。

factLabel.numberOfLines = 0;
factLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize];
factLabel.frame = CGRectMake(factLabel.frame.Origin.x, factLabel.frame.Origin.y, expectSize.width, expectSize.height);
337
Martin Babacaev

minimumFontSizeはiOS 6では推奨されなくなりました。minimumScaleFactorを使用できます。

yourLabel.adjustsFontSizeToFitWidth=YES;
yourLabel.minimumScaleFactor=0.5;

これはラベルとテキストの幅に従ってあなたのフォントサイズを大事にします。

66
Amit Singh

@Eyal Ben Dovの回答に基づいて、カテゴリを作成して他のアプリ内での使用を柔軟にすることができます。

Obs .: iOS 7と互換性を持たせるために彼のコードを更新しました

- ヘッダーファイル

#import <UIKit/UIKit.h>

@interface UILabel (DynamicFontSize)

-(void) adjustFontSizeToFillItsContents;

@end

- 実装ファイル

#import "UILabel+DynamicFontSize.h"

@implementation UILabel (DynamicFontSize)

#define CATEGORY_DYNAMIC_FONT_SIZE_MAXIMUM_VALUE 35
#define CATEGORY_DYNAMIC_FONT_SIZE_MINIMUM_VALUE 3

-(void) adjustFontSizeToFillItsContents
{
    NSString* text = self.text;

    for (int i = CATEGORY_DYNAMIC_FONT_SIZE_MAXIMUM_VALUE; i>CATEGORY_DYNAMIC_FONT_SIZE_MINIMUM_VALUE; i--) {

        UIFont *font = [UIFont fontWithName:self.font.fontName size:(CGFloat)i];
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];

        CGRect rectSize = [attributedText boundingRectWithSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

        if (rectSize.size.height <= self.frame.size.height) {
            self.font = [UIFont fontWithName:self.font.fontName size:(CGFloat)i];
            break;
        }
    }

}

@end

- Usage

#import "UILabel+DynamicFontSize.h"

[myUILabel adjustFontSizeToFillItsContents];

乾杯

24

それは2015年です。私はそれが複数の行で動作するようにするためにSwiftでiOSとXCodeの最新バージョンのためにそれをする方法を説明するブログ記事を見つけるために行かなければなりませんでした。

  1. 「自動縮小」を「最小フォントサイズ」に設定します。
  2. フォントを望ましい最大のフォントサイズに設定します(私は20を選びました)
  3. 「改行」を「折り返し」から「末尾の切り捨て」に変更します。

出典: http://beckyhansmeyer.com/2015/04/09/autoshrinking-text-in-a-multiline-uilabel/

20
zavtra

単一行 - 2つの方法があります、あなたは単に変えることができます。

1 - 実用的(Swift 3)

次のコードを追加するだけです

    yourLabel.numberOfLines = 1;
    yourLabel.minimumScaleFactor = 0.7;
    yourLabel.adjustsFontSizeToFitWidth = true;

2 - UILabel Attributesインスペクタを使う

i- Select your label- Set number of lines 1.
ii- Autoshrink-  Select Minimum Font Scale from drop down
iii- Set Minimum Font Scale value as you wish , I have set 0.7 as in below image. (default is 0.5)

enter image description here

19
Devendra Singh

迅速なバージョン:

textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = 0.5
12
Esqarrouth

これがUILabelのSwift拡張です。バイナリ検索アルゴリズムを実行して、ラベルの境界の幅と高さに基づいてフォントのサイズを変更します。 iOS 9と自動レイアウトで動作することがテスト済みです。

SAGE:ここで、<label>はフォントのサイズ変更が必要な事前定義のUILabelです。

<label>.fitFontForSize()

デフォルトでは、この関数は5ptから300ptのフォントサイズの範囲内で検索し、そのテキストが境界内で「完全に」収まるようにフォントを設定します(1.0pt以内の精度)。たとえば、1ptラベルの現在のフォントサイズの間を.1ptsの範囲内で正確に検索するようにパラメータを定義できます。 :

<label>.fitFontForSize(1.0, maxFontSize: <label>.font.pointSize, accuracy:0.1)

ファイルに次のコードをコピー/貼り付け

extension UILabel {

    func fitFontForSize(var minFontSize : CGFloat = 5.0, var maxFontSize : CGFloat = 300.0, accuracy : CGFloat = 1.0) {
        assert(maxFontSize > minFontSize)
        layoutIfNeeded() // Can be removed at your own discretion
        let constrainedSize = bounds.size
        while maxFontSize - minFontSize > accuracy {
            let midFontSize : CGFloat = ((minFontSize + maxFontSize) / 2)
            font = font.fontWithSize(midFontSize)
            sizeToFit()
            let checkSize : CGSize = bounds.size
            if  checkSize.height < constrainedSize.height && checkSize.width < constrainedSize.width {
                minFontSize = midFontSize
            } else {
                maxFontSize = midFontSize
            }
        }
        font = font.fontWithSize(minFontSize)
        sizeToFit()
        layoutIfNeeded() // Can be removed at your own discretion
    }

}

注:それぞれのlayoutIfNeeded()呼び出しはあなたの判断で削除することができます。

7
Avi Frankl

ちょっと洗練されていませんが、これはうまくいくはずです。例えば、最大フォントサイズを28にして、uilabelを120x120に制限したいとしましょう。

magicLabel.numberOfLines = 0;
magicLabel.lineBreakMode = NSLineBreakByWordWrapping;
...
magicLabel.text = text;
    for (int i = 28; i>3; i--) {
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:(CGFloat)i] constrainedToSize:CGSizeMake(120.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        if (size.height < 120) {
            magicLabel.font = [UIFont systemFontOfSize:(CGFloat)i];
            break;
        }
    }
4
Eyal Ben Dov

SizeToFitメッセージをUITextViewに送信するだけです。テキストに合わせて高さを調整します。それ自身の幅や原点は変わりません。

[textViewA1 sizeToFit];
1
codercat

これは、アニメーション化されたフォントサイズの変更を実装するUILabelサブクラスの塗りつぶしコードです。

@interface SNTextLayer : CATextLayer

@end

@implementation SNTextLayer

- (void)drawInContext:(CGContextRef)ctx {
    // We override this to make text appear at the same vertical positon as in UILabel
    // (otherwise it's shifted tdown)
    CGFloat height = self.bounds.size.height;
    float fontSize = self.fontSize;
    // May need to adjust this somewhat if it's not aligned perfectly in your implementation
    float yDiff = (height-fontSize)/2 - fontSize/10;

    CGContextSaveGState(ctx);
    CGContextTranslateCTM(ctx, 0.0, yDiff);
    [super drawInContext:ctx];
     CGContextRestoreGState(ctx);
}

@end

@interface SNAnimatableLabel ()

@property CATextLayer* textLayer;

@end

@interface SNAnimatableLabel : UILabel

- (void)animateFontToSize:(CGFloat)fontSize withDuration:(double)duration;

@end



@implementation SNAnimatableLabel


- (void)awakeFromNib {
    [super awakeFromNib];
    _textLayer = [SNTextLayer new];
    _textLayer.backgroundColor = self.backgroundColor.CGColor;
    _textLayer.foregroundColor = self.textColor.CGColor;
    _textLayer.font = CGFontCreateWithFontName((CFStringRef)self.font.fontName);
    _textLayer.frame = self.bounds;
    _textLayer.string = self.text;
    _textLayer.fontSize = self.font.pointSize;
    _textLayer.contentsScale = [UIScreen mainScreen].scale;
    [_textLayer setPosition: CGPointMake(CGRectGetMidX(_textLayer.frame), CGRectGetMidY(_textLayer.frame))];
    [_textLayer setAnchorPoint: CGPointMake(0.5, 0.5)];
    [_textLayer setAlignmentMode: kCAAlignmentCenter];
    self.textColor = self.backgroundColor;
    // Blend text with background, so that it doens't interfere with textlayer text
    [self.layer addSublayer:_textLayer];
    self.layer.masksToBounds = NO;
}

- (void)setText:(NSString *)text {
    _textLayer.string = text;
    super.text = text;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    // Need to enlarge the frame, otherwise the text may get clipped for bigger font sizes
    _textLayer.frame = CGRectInset(self.bounds, -5, -5);
}

- (void)animateFontToSize:(CGFloat)fontSize withDuration:(double)duration {
    [CATransaction begin];
    [CATransaction setAnimationDuration:duration];
    _textLayer.fontSize = fontSize;
    [CATransaction commit];
}
0
videolist

この解決策は複数行で機能します。

いくつかの記事を読んで、自動的にテキストを拡大縮小し、指定されたラベルサイズ内に収まるように行数を調整する関数が必要になった後、私は自分自身で関数を書きました。 (つまり、短い文字列は1行にうまく収まり、大量のラベルフレームを使用しますが、長い文字列は自動的に2行または3行に分割され、それに応じてサイズが調整されます)。

自由に再利用して、必要に応じて微調整してください。初期ラベルフレームが設定されるようにviewDidLayoutSubviewsが終了した後に必ずそれを呼び出すようにしてください。

+ (void)setFontForLabel:(UILabel *)label withMaximumFontSize:(float)maxFontSize andMaximumLines:(int)maxLines {
    int numLines = 1;
    float fontSize = maxFontSize;
    CGSize textSize; // The size of the text
    CGSize frameSize; // The size of the frame of the label
    CGSize unrestrictedFrameSize; // The size the text would be if it were not restricted by the label height
    CGRect originalLabelFrame = label.frame;

    frameSize = label.frame.size;
    textSize = [label.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize: fontSize]}];

    // Work out the number of lines that will need to fit the text in snug
    while (((textSize.width / numLines) / (textSize.height * numLines) > frameSize.width / frameSize.height) && (numLines < maxLines)) {
        numLines++;
    }

    label.numberOfLines = numLines;

    // Get the current text size
    label.font = [UIFont systemFontOfSize:fontSize];
    textSize = [label.text boundingRectWithSize:CGSizeMake(frameSize.width, CGFLOAT_MAX)
                                        options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                     attributes:@{NSFontAttributeName : label.font}
                                        context:nil].size;

    // Adjust the frame size so that it can fit text on more lines
    // so that we do not end up with truncated text
    label.frame = CGRectMake(label.frame.Origin.x, label.frame.Origin.y, label.frame.size.width, label.frame.size.width);

    // Get the size of the text as it would fit into the extended label size
    unrestrictedFrameSize = [label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:numLines].size;

    // Keep reducing the font size until it fits
    while (textSize.width > unrestrictedFrameSize.width || textSize.height > frameSize.height) {
        fontSize--;
        label.font = [UIFont systemFontOfSize:fontSize];
        textSize = [label.text boundingRectWithSize:CGSizeMake(frameSize.width, CGFLOAT_MAX)
                                            options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                         attributes:@{NSFontAttributeName : label.font}
                                            context:nil].size;
        unrestrictedFrameSize = [label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:numLines].size;
    }

    // Set the label frame size back to original
    label.frame = originalLabelFrame;
}
0
aaroncatlin

Swift 2.0 Version:

private func adapteSizeLabel(label: UILabel, sizeMax: CGFloat) {
     label.numberOfLines = 0
     label.lineBreakMode = NSLineBreakMode.ByWordWrapping
     let maximumLabelSize = CGSizeMake(label.frame.size.width, sizeMax);
     let expectSize = label.sizeThatFits(maximumLabelSize)
     label.frame = CGRectMake(label.frame.Origin.x, label.frame.Origin.y, expectSize.width, expectSize.height)
}
0
Phil