web-dev-qa-db-ja.com

Textに従ってUILabelの高さを動的に取得すると、iOS 7.0とiOS 6.1で異なる値が返される

UILabelの高さを動的に取得するためにこのメソッドを使用しています:

+(CGSize) GetSizeOfLabelForGivenText:(UILabel*)label Font:(UIFont*)fontForLabel Size:  (CGSize)LabelSize{
    label.numberOfLines = 0;
    CGSize labelSize = [label.text sizeWithFont:fontForLabel constrainedToSize:LabelSize lineBreakMode:NSLineBreakByCharWrapping];
    return (labelSize);
}

このソリューションでは、コードがiOS 8以下で実行されている場合、UILabelの正確なサイズを取得していますが、iOS7でアプリケーションを実行すると、異なる値が返されます。

23
Sumeet Mourya

以下のように、フレームを動的に設定する必要があります。

IOS 6からiOS 12.2でテスト済み

スイフト:

let constrainedSize = CGSize(width: self.titleLable.frame.size.width, height:9999)

let attributesDictionary = [NSAttributedString.Key.font: UIFont.init(name: "HelveticaNeue", size: 11.0)]

let string = NSAttributedString.init(string: "textToShow", attributes: attributesDictionary as [NSAttributedString.Key : Any])

var requiredHeight = string.boundingRect(with: constrainedSize, options: .usesLineFragmentOrigin, context: nil)


if (requiredHeight.size.width > self.titleLable.frame.size.width) {
    requiredHeight = CGRect(x: 0, y: 0, width: self.titleLable.frame.size.width, height: requiredHeight.size.height)
}
var newFrame = self.titleLable.frame
newFrame.size.height = requiredHeight.size.height
self.titleLable.frame = newFrame

目的C:

CGSize constrainedSize = CGSizeMake(self.resizableLable.frame.size.width  , 9999);

NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName,
                                      nil];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"textToShow" attributes:attributesDictionary];

CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

if (requiredHeight.size.width > self.resizableLable.frame.size.width) {
    requiredHeight = CGRectMake(0,0, self.resizableLable.frame.size.width, requiredHeight.size.height);
}
CGRect newFrame = self.resizableLable.frame;
newFrame.size.height = requiredHeight.size.height;
self.resizableLable.frame = newFrame;
26
preetam

これが幅と高さの総合的な解決策です。これらをAppDelegateに追加します。

+(void)fixHeightOfThisLabel:(UILabel *)aLabel
{
    aLabel.frame = CGRectMake(aLabel.frame.Origin.x,
                              aLabel.frame.Origin.y,
                              aLabel.frame.size.width,
                              [AppDelegate heightOfTextForString:aLabel.text
                                                         andFont:aLabel.font
                                                         maxSize:CGSizeMake(aLabel.frame.size.width, MAXFLOAT)]);
}

+(CGFloat)heightOfTextForString:(NSString *)aString andFont:(UIFont *)aFont maxSize:(CGSize)aSize
{
    // iOS7
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        CGSize sizeOfText = [aString boundingRectWithSize: aSize
                                                  options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                               attributes: [NSDictionary dictionaryWithObject:aFont
                                                                                       forKey:NSFontAttributeName]
                                                  context: nil].size;

        return ceilf(sizeOfText.height);
    }

    // iOS6
    CGSize textSize = [aString sizeWithFont:aFont
                          constrainedToSize:aSize
                              lineBreakMode:NSLineBreakByWordWrapping];
    return ceilf(textSize.height;
}

+(void)fixWidthOfThisLabel:(UILabel *)aLabel
{
    aLabel.frame = CGRectMake(aLabel.frame.Origin.x,
                              aLabel.frame.Origin.y,
                                [AppDelegate widthOfTextForString:aLabel.text
                                                          andFont:aLabel.font
                                                          maxSize:CGSizeMake(MAXFLOAT, aLabel.frame.size.height)],
                              aLabel.frame.size.height);
}

+(CGFloat)widthOfTextForString:(NSString *)aString andFont:(UIFont *)aFont maxSize:(CGSize)aSize
{
    // iOS7
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        CGSize sizeOfText = [aString boundingRectWithSize: aSize
                                                  options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                               attributes: [NSDictionary dictionaryWithObject:aFont
                                                                                       forKey:NSFontAttributeName]
                                                  context: nil].size;

        return ceilf(sizeOfText.width);
    }

    // iOS6
    CGSize textSize = [aString sizeWithFont:aFont
                          constrainedToSize:aSize
                              lineBreakMode:NSLineBreakByWordWrapping];
    return ceilf(textSize.width);
}

次に、これを使用するには、ラベルのテキストを設定します。

label.numberOfLines = 0;
label.text = @"Everyone loves Stack OverFlow";

そして電話:

[AppDelegate fixHeightOfThisLabel:label];

注:ラベルのnumberOfLinesは0に設定する必要があります。

5
Andrew Bennett

システムフォントのいずれかを使用している場合、iOS 7で変更されたため、サイズが異なります。


また、sizeWithFont:constrainedToSize:lineBreakMode:はiOS 7では非推奨です。代わりに sizeWithAttributes: を使用します(iOS 7を使用している場合)

4
liamnichols

受け入れられた答えは私を満足させなかったので、コードでこれを掘り下げなければなりませんでした:

CGSize possibleSize = [string sizeWithFont:[UIFont fontWithName:@"HelveticaNeue" size:10] //font you are using
                          constrainedToSize:CGSizeMake(skillsMessage.frame.size.width,9999)
                              lineBreakMode:NSLineBreakByWordWrapping];


CGRect newFrame = label.frame;
newFrame.size.height = possibleSize.height;
label.frame = newFrame;
2
stackOverFlew

受け入れられた答えが長すぎます。以下を使用できます。

+(CGSize) GetSizeOfLabelForGivenText:(UILabel*)label Font:(UIFont*)fontForLabel Size:  (CGSize) constraintSize{
    label.numberOfLines = 0;
    CGRect labelRect = [label.text boundingRectWithSize:constraintSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:fontForLabel} context:nil];
    return (labelRect.size);
}
1
Armin

私はいつもsizeThatFits:

CGRect frame = myLabel.frame;
CGSize constraint = CGSizeMake(CGRectGetWidth(myLabel.frame), 20000.0f);
CGSize size = [myLabel sizeThatFits:constraint];
frame.size.height = size.height;
myLabel.frame = frame;

これを試すことができます

1
Js Lim

このコードで取得する高さ(上記のこの質問で書いた方法)に関係なく、フロート値で高さを提供します(86.4)しかし、(86.4)のままの値の代わりに、ceil (87)で高さから値を取得する必要があります。このアプローチで問題を解決しました。そして、あなたの答えに感謝します。

0
Sumeet Mourya

この方法は、iOS 7からiOS 11.4で使用およびテストされています

+ (CGFloat)getLabelHeight:(UILabel*)label
{
    NSParameterAssert(label);
    CGSize limitLabel = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
    CGSize size;

    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize labelBox = [label.text boundingRectWithSize: limitLabel
                                                  options: NSStringDrawingUsesLineFragmentOrigin
                                               attributes: @{ NSFontAttributeName:label.font }
                                                  context: context].size;

    size = CGSizeMake(ceil(labelBox.width), ceil(labelBox.height));
    return size.height;
}

したがって、次のように使用できます。

CGFloat sizeOfFontTest = 12.0;
    UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 100, 0)];
    [testLabel setFont: [UIFont systemFontOfSize: sizeOfFontTest]];
    [testLabel setText: @"Hello Stackoverflow Large String Example"];

    CGFloat heightTestLabel = [self getLabelHeight: testLabel];

    [testLabel setFrame: CGRectMake(testLabel.frame.Origin.x, testLabel.frame.Origin.y, testLabel.frame.size.width, heightAddrsLab)];
    [testLabel setNumberOfLines: sizeOfFontTest / heightTestLabel];
0
Ladd.c

超シンプル。テキストの領域を取得し、幅で分割し、フォントに合う最も近い高さに切り上げます。

+ (CGFloat)heightForText:(NSString*)text font:(UIFont*)font withinWidth:(CGFloat)width {
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:font}];
    CGFloat area = size.height * size.width;
    CGFloat height = roundf(area / width);
    return ceilf(height / font.lineHeight) * font.lineHeight;
}

非常にプラグアンドプレイのソリューション。特に動的なサイズのUITableViewCellsの場合、ヘルパークラスで多く使用します。

これが将来他の人を助けることを願っています!

0
AlexKoren

これが私がついに思いついたものであり、これがあなたを助けることを願っています。 iOSのバージョンをApple自体が iOS 7 UI移行ガイド で行っています。 iOS 7以降では、「-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size」を使用します。

+ (CGSize)getStringBoundingSize:(NSString*)string forWidth:(CGFloat)width withFont:(UIFont*)font{

    CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
        // for iOS 6.1 or earlier
        // temporarily suppress the warning and then turn it back on
        // since sizeWithFont:constrainedToSize: deprecated on iOS 7 or later
        #pragma clang diagnostic Push
        #pragma clang diagnostic ignored "-Wdeprecated-declarations"
            maxSize = [string sizeWithFont:font constrainedToSize:maxSize];
        #pragma clang diagnostic pop

    } else {
        // for iOS 7 or later
        maxSize = [string sizeWithAttributes:@{NSFontAttributeName:font}];

    }
    return maxSize;
}
0

テキストに従ってラベルの高さを動的に設定する必要がある状況があります。 Xcode 7.1を使用しており、プロジェクトの展開ターゲットは7.0ですが、iOS 9シミュレーターでテストし、次のソリューションが機能します。解決策は次のとおりです。まず、次のような辞書を作成します。

NSDictionary *attributes = @{NSFontAttributeName:self.YOUR_LABEL.font};

次に、テキストの高さと幅を計算し、新しく作成した辞書を渡します。

    CGRect rect = [YOUR_TEXT_STRING boundingRectWithSize:CGSizeMake(LABEL_WIDTH, CGFLOAT_MAX)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attributes
                                          context:nil];

次に、LABELのフレームを設定します。

    self.YOUR_LABEL.frame = CGRectMake(self.YOUR_LABEL.frame.Origin.x, self.YOUR_LABEL.frame.Origin.y, self.YOUR_LABEL.frame.size.width, rect.size.height);

このISテキストに応じてラベルのフレームを正常に設定する方法。

0
Zulqarnain

メソッドsizeWithFont:constrainedToSize:lineBreakMode:はiOS7では非推奨です。代わりにsizeWithAttributes:を使用する必要があります。

例:

NSDictionary *fontAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:15]};
CGSize textSize = [self.myLabel.text sizeWithAttributes:fontAttributes];
CGFloat textWidth = textSize.width;
CGFloat textHeight = textSize.height;
0
Groot