2013-09-06 10 views
12

sizeWithFont:constrainedToSize:lineBreakMode:メソッドがiOS7で廃止予定の場合は、UILabelのサイズを動的に調整してテキストに合わせるにはどうすればよいですか?sizeWithFont:constrainedToSize:lineBreakMode:iOS7では非推奨

+1

これは明らかに興味があります。代わりにboundingRectを使ってみましたが、上記のように制約を入力することはできません。 – Tim

+0

boundingRectWithSizeの何が問題ですか:options:attributes:context? – peko

+0

私はそれを悪用しているに違いない、私はそれを別のものにします! – Tim

答えて

8

私はこれを使用して終了しました。私のために働く。これはIBOutletsオブジェクトでは機能しませんが、uitableviewのheightForRowAtIndexPath:メソッドでテキストの高さを動的に計算する場合に便利です。

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

CGRect frame = [label.text boundingRectWithSize:CGSizeMake(263, 2000.0) 
                options:NSStringDrawingUsesLineFragmentOrigin 
                attributes:attributesDictionary 
                context:nil]; 

CGSize size = frame.size; 
+1

これはIBOutlet UILabelで全く機能していないようです – Tim

+0

これは自動レイアウトでは「現状のまま」動作しません。私の解決策をここにチェックしてください:http://stackoverflow.com/a/18933978/557054 –

6

これは(あなたが戻ってプログラム的に必要であれば、それらすべてを設定する必要があります)iOS6およびiOS7に動作するはずですが、あなたのラベルの制約を破るます:

-(void)resizeHeightForLabel: (UILabel*)label { 
    label.numberOfLines = 0; 
    UIView *superview = label.superview; 
    [label removeFromSuperview]; 
    [label removeConstraints:label.constraints]; 
    CGRect labelFrame = label.frame; 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) { 
     CGRect expectedFrame = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, 9999) 
                 options:NSStringDrawingUsesLineFragmentOrigin 
                attributes:[NSDictionary dictionaryWithObjectsAndKeys: 
                   label.font, NSFontAttributeName, 
                   nil] 
                 context:nil]; 
     labelFrame.size = expectedFrame.size; 
     labelFrame.size.height = ceil(labelFrame.size.height); //iOS7 is not rounding up to the nearest whole number 
    } else { 
#pragma GCC diagnostic ignored "-Wdeprecated-declarations" 
     labelFrame.size = [label.text sizeWithFont:label.font 
           constrainedToSize:CGSizeMake(label.frame.size.width, 9999) 
            lineBreakMode:label.lineBreakMode]; 
#pragma GCC diagnostic warning "-Wdeprecated-declarations" 
    } 
    label.frame = labelFrame; 
    [superview addSubview:label]; 
} 

あなたのViewControllerに、このメソッドを追加し、それを使用しますこのように:

[self resizeHeightForLabel:myLabel]; 
//set new constraints here if needed 
+1

これは命の恩人です!私が解決しようとしているシンプルな問題のように、私がこれを使いこなすのに費やした時間は非現実的です。 –

+0

私はこれを使用していますが、ラベルのサイズを変更しますが、ラベルがスーパービューに再追加されたときに、原点がフレームに正しく設定されていることを確認することはできますが、位置は間違っています –

+0

@PeteMartinはあなたですかスーパービューの1つがUITableViewCellや他のキャッシュされたUI要素ではないことを確認してください。その場合は、いくつかの回避策が必要です。 –