322

UILabel(動的テキストの長い行) に次のテキストがあるとします。

エイリアンの軍隊はチームの数をはるかに上回っているため、プレイヤーはポスト黙示録的な世界を有利に利用する必要があります。たとえば、ゴミ箱、柱、車、瓦礫、その他のオブジェクトの後ろに隠れる必要があります。

UILabel'sテキストが収まるように高さのサイズを変更したいのですが、次のプロパティを使用UILabelして、テキストを折り返すようにしています。

myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;

正しい方向に進んでいない場合はお知らせください。ありがとう。

4

34 に答える 34

415

sizeWithFont constrainedToSize:lineBreakMode:使用する方法です。使用方法の例を以下に示します。

//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];   

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
于 2009-01-15T15:01:19.127 に答える
247

あなたは正しい方向に進んでいました。あなたがする必要があるのは、次のとおりです。

myUILabel.numberOfLines = 0;
myUILabel.text = @"Enter large amount of text here";
[myUILabel sizeToFit];
于 2009-08-20T04:45:20.967 に答える
45

iOS 6 では、Apple はUILabelに、ラベルの動的な垂直方向のサイズ変更を大幅に簡素化するプロパティpreferredMaxLayoutWidthを追加しました。

このプロパティをlineBreakMode = NSLineBreakByWordWrappingおよびsizeToFitメソッドと組み合わせて使用​​すると、テキスト全体が収まる高さに UILabel インスタンスのサイズを簡単に変更できます。

iOS ドキュメントからの引用:

preferredMaxLayoutWidth 複数行ラベルの優先最大幅 (ポイント単位)。

解説 このプロパティは、レイアウトの制約がラベルに適用されたときに、ラベルのサイズに影響します。レイアウト中に、テキストがこのプロパティで指定された幅を超える場合、追加のテキストは 1 つまたは複数の新しい行に流れ、それによってラベルの高さが増加します。

サンプル:

...
UILabel *status = [[UILabel alloc] init];
status.lineBreakMode = NSLineBreakByWordWrapping;
status.numberOfLines = 5; // limits to 5 lines; use 0 for unlimited.

[self addSubview:status]; // self here is the parent view

status.preferredMaxLayoutWidth = self.frame.size.width; // assumes the parent view has its frame already set.

status.text = @"Some quite lengthy message may go here…";
[status sizeToFit];
[status setNeedsDisplay];
...
于 2013-11-04T21:14:05.210 に答える
43

1行のコードを追加せずに、この動作を完全に確認してください。(自動レイアウトを使用)

ご要望に応じてデモを作成しました。以下のリンクからダウンロードして、

UIView と UILabel の自動サイズ変更

ステップバイステップガイド:-

ステップ 1 :-制約を UIView に設定します

1) リーディング 2) トップ 3) トレーリング (メインビューより)

ここに画像の説明を入力

ステップ 2 :-制約をラベル 1 に設定します

1) リーディング 2) トップ 3) トレーリング (スーパービューより)

ここに画像の説明を入力

ステップ 3 :-制約をラベル 2 に設定します

1) リーディング 2) トレーリング (スーパービューより)

ここに画像の説明を入力

ステップ 4 :- 最もトリッキーなのは、 UIView から UILabel にボタンを与えることです。

ここに画像の説明を入力

ステップ 5 :- (オプション) UIButton に制約を設定します

1) リーディング 2) ボトム 3) トレーリング 4) 固定高さ (メインビューより)

ここに画像の説明を入力

出力:-

ここに画像の説明を入力

注:- Label プロパティで Number of lines =0 を設定していることを確認してください。

ここに画像の説明を入力

この情報が、UILabel の高さに応じて UIView の自動サイズ変更とテキストに応じた UILabel の自動サイズ変更を理解するのに十分であることを願っています。

于 2016-04-26T10:52:51.350 に答える
39

これをプログラムで行う代わりに、設計中に Storyboard/XIB でこれを行うことができます。

  • 属性インスペクタでUIlabel の行数プロパティを0に設定します。
  • 次に、要件に従って、幅の制約/(または) 先頭と末尾の制約を設定します。
  • 次に、最小値で高さの制約を設定します。最後に、追加した高さの制約を選択し、サイズ インスペクターで属性インスペクターの横にあるものを選択し、高さの制約の関係equal to - greater thanから変更します。
于 2015-06-18T19:08:10.583 に答える
15

助けてくれてありがとう、これが私が試したコードで、私のために働いています

   UILabel *instructions = [[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)];
   NSString *text = @"First take clear picture and then try to zoom in to fit the ";
   instructions.text = text;
   instructions.textAlignment = UITextAlignmentCenter;
   instructions.lineBreakMode = NSLineBreakByWordWrapping;
   [instructions setTextColor:[UIColor grayColor]];

   CGSize expectedLabelSize = [text sizeWithFont:instructions.font 
                                constrainedToSize:instructions.frame.size
                                    lineBreakMode:UILineBreakModeWordWrap];

    CGRect newFrame = instructions.frame;
    newFrame.size.height = expectedLabelSize.height;
    instructions.frame = newFrame;
    instructions.numberOfLines = 0;
    [instructions sizeToFit];
    [self addSubview:instructions];
于 2010-11-23T17:20:47.997 に答える
11

sizeWithFont は非推奨なので、代わりにこれを使用します。

これはラベル固有の属性を取得します。

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text{

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];

    return ceil(rect.size.height);
}
于 2014-11-13T23:40:58.467 に答える
6

TableViewController's (UITableViewCell *)tableView:cellForRowAtIndexPath 次の方法でメソッドを実装できます(例):

#define CELL_LABEL_TAG 1

- (UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = @"my long text";

    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero  reuseIdentifier:identifier] autorelease];
    }

    CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
    CGFloat height = [self textHeight:text] + 10;
    CGRect frame = CGRectMake(10.0f, 10.0f, width, height);

    UILabel *cellLabel = [[UILabel alloc] initWithFrame:frame];
    cellLabel.tag = CELL_LABEL_TAG;
    cellLabel.textColor = [UIColor blackColor];
    cellLabel.backgroundColor = [UIColor clearColor];
    cellLabel.textAlignment = UITextAlignmentLeft;
    cellLabel.font = [UIFont systemFontOfSize:12.0f];
    [cell.contentView addSubview:cellLabel];
    [cellLabel release];

    return cell;
}

UILabel *label = (UILabel *)[cell viewWithTag:CELL_LABEL_TAG];
label.text = text;
label.numberOfLines = 0;
[label sizeToFit];
return cell;

また、NSStringsizeWithFont:constrainedToSize:lineBreakMode:メソッドを使用して、テキストの高さを計算します。

于 2009-01-15T14:10:57.480 に答える
6

カテゴリバージョンは次のとおりです。

UILabel+AutoSize.h # インポート

@interface UILabel (AutoSize)

- (void) autosizeForWidth: (int) width;

@end

UILabel+AutoSize.m

#import "UILabel+AutoSize.h"

@implementation UILabel (AutoSize)

- (void) autosizeForWidth: (int) width {
    self.lineBreakMode = UILineBreakModeWordWrap;
    self.numberOfLines = 0;
    CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
    CGSize expectedLabelSize = [self.text sizeWithFont:self.font constrainedToSize:maximumLabelSize lineBreakMode:self.lineBreakMode];
    CGRect newFrame = self.frame;
    newFrame.size.height = expectedLabelSize.height;
    self.frame = newFrame;
}

@end
于 2013-04-10T17:58:02.327 に答える
5

UILabel の動的な高さを計算する私のアプローチ。

    let width = ... //< width of this label 
    let text = ... //< display content

    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.preferredMaxLayoutWidth = width

    // Font of this label.
    //label.font = UIFont.systemFont(ofSize: 17.0)
    // Compute intrinsicContentSize based on font, and preferredMaxLayoutWidth
    label.invalidateIntrinsicContentSize() 
    // Destination height
    let height = label.intrinsicContentSize.height

ラップして機能する:

func computeHeight(text: String, width: CGFloat) -> CGFloat {
    // A dummy label in order to compute dynamic height.
    let label = UILabel()

    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.font = UIFont.systemFont(ofSize: 17.0)

    label.preferredMaxLayoutWidth = width
    label.text = text
    label.invalidateIntrinsicContentSize()

    let height = label.intrinsicContentSize.height
    return height
}
于 2017-07-19T06:02:18.130 に答える
4

私にとって最も簡単でより良い方法は、高さの制約をラベルに適用し、ストーリーボードで優先度を low、つまり (250) に設定することでした。

したがって、ストーリーボードのおかげで、高さと幅をプログラムで計算することについて心配する必要はありません。

于 2016-05-16T16:43:07.110 に答える
3

更新された方法

+ (CGFloat)heightForText:(NSString*)text font:(UIFont*)font withinWidth:(CGFloat)width {

    CGSize constraint = CGSizeMake(width, 20000.0f);
    CGSize size;

    CGSize boundingBox = [text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:font}
                                                  context:nil].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}
于 2015-07-06T12:21:58.313 に答える
3

これは、Objective-c を使用して UILabel の高さを取得するための 1 行のコードです。

labelObj.numberOfLines = 0;
CGSize neededSize = [labelObj sizeThatFits:CGSizeMake(screenWidth, CGFLOAT_MAX)];

.height を使用すると、次のようにラベルの高さが得られます。

neededSize.height
于 2017-03-07T13:22:03.800 に答える
2
UILabel *itemTitle = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 10,100, 200.0f)];
itemTitle.text = @"aseruy56uiytitfesh";
itemTitle.adjustsFontSizeToFitWidth = NO;
itemTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
itemTitle.font = [UIFont boldSystemFontOfSize:18.0];
itemTitle.textColor = [UIColor blackColor];
itemTitle.shadowColor = [UIColor whiteColor];
itemTitle.shadowOffset = CGSizeMake(0, 1);
itemTitle.backgroundColor = [UIColor blueColor];
itemTitle.lineBreakMode = UILineBreakModeWordWrap;
itemTitle.numberOfLines = 0;
[itemTitle sizeToFit];
[self.view addSubview:itemTitle];

ここでこれを使用して、すべてのプロパティがラベルで使用され、itemTitle.text のテキストを次のように増やしてテストします。

itemTitle.text = @"diofgorigjveghnhkvjteinughntivugenvitugnvkejrfgnvkhv";

必要に応じて完璧な答えが表示されます

于 2013-06-27T12:02:20.673 に答える
2

メソッドとしても使用できます。@Pyjamasamは非常に真実なので、私はその方法を作っています。他の誰かに役立つかもしれません

-(CGRect)setDynamicHeightForLabel:(UILabel*)_lbl andMaxWidth:(float)_width{
    CGSize maximumLabelSize = CGSizeMake(_width, FLT_MAX);

    CGSize expectedLabelSize = [_lbl.text sizeWithFont:_lbl.font constrainedToSize:maximumLabelSize lineBreakMode:_lbl.lineBreakMode];

    //adjust the label the the new height.
    CGRect newFrame = _lbl.frame;
    newFrame.size.height = expectedLabelSize.height;
    return newFrame;
}

そして、このように設定するだけです

label.frame = [self setDynamicHeightForLabel:label andMaxWidth:300.0];
于 2014-01-20T12:19:57.467 に答える
2

この投稿をありがとう。とても助かりました。私の場合、別のView Controllerでテキストも編集しています。私が使用するときに気づいた:

[cell.contentView addSubview:cellLabel];

tableView:cellForRowAtIndexPath: メソッドでは、セルを編集するたびに、ラベル ビューが前のビューの上に継続的にレンダリングされていました。テキストがピクセル化され、何かが削除または変更されると、以前のバージョンが新しいバージョンの下に表示されました。これが私が問題を解決した方法です:

if ([[cell.contentView subviews] count] > 0) {
    UIView *test = [[cell.contentView subviews] objectAtIndex:0];
    [test removeFromSuperview];
}
[cell.contentView insertSubview:cellLabel atIndex:0];

変な重ね着はもう必要ありません。これを処理するより良い方法があれば、私に知らせてください。

于 2009-02-20T22:54:43.137 に答える
1
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cellIdentifier = @"myCell";
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell.myUILabel.lineBreakMode = UILineBreakModeWordWrap;        
    cell.myUILabel.numberOfLines = 0;
    cell.myUILabel.text = @"Some very very very very long text....."
    [cell.myUILabel.criterionDescriptionLabel sizeToFit];    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    CGFloat rowHeight = cell.myUILabel.frame.size.height + 10;

    return rowHeight;    
}
于 2012-08-29T07:29:26.613 に答える
1

スウィフト 2:

    yourLabel.text = "your very long text"
    yourLabel.numberOfLines = 0
    yourLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    yourLabel.frame.size.width = 200
    yourLabel.frame.size.height = CGFloat(MAXFLOAT)
    yourLabel.sizeToFit()

興味深い行は、 aを最大フロートにsizeToFit()設定することと関連しています。これにより、長いテキストのスペースが確保されますが、必要なもののみを使用するように強制されますが、.frame.size.heightsizeToFit().frame.size.height

.backgroundColorデバッグ目的で を設定することをお勧めします。これにより、各ケースでレンダリングされているフレームを確認できます。

于 2015-11-26T18:51:14.560 に答える
1

この方法は完璧な高さを与えます

-(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
CGSize constraint = CGSizeMake(width , 20000.0f);
CGSize title_size;
float totalHeight;


title_size = [text boundingRectWithSize:constraint
                                options:NSStringDrawingUsesLineFragmentOrigin
                             attributes:@{ NSFontAttributeName : font }
                                context:nil].size;

totalHeight = ceil(title_size.height);

CGFloat height = MAX(totalHeight, 40.0f);
return height;
}
于 2016-04-07T14:00:14.197 に答える
1

最後に、それはうまくいきました。君たちありがとう。

メソッドでラベルのサイズを変更しようとしていたため、機能しませんでしたheightForRowAtIndexPath

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

そして(ええ、ばかげた私)、私はcellForRowAtIndexPathメソッドでラベルのサイズをデフォルトに変更していました-私は以前に書いたコードを見落としていました:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
于 2009-01-16T07:25:17.907 に答える
1

一行は、クリスの答えが間違っているということです。

newFrame.size.height = maximumLabelSize.height;

する必要があります

newFrame.size.height = expectedLabelSize.height;

それ以外は、正しい解決策です。

于 2009-05-21T06:31:44.597 に答える
0

この方法は、iOS 6 と 7 の両方で機能します。

- (float)heightForLabelSize:(CGSize)maximumLabelSize  Font:(UIFont *)font String:(NSString*)string {

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
    NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:font forKey: NSFontAttributeName];

    CGSize adjustedLabelSize = [string maximumLabelSize
                                                                  options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
                                                               attributes:stringAttributes context:nil].size;
    return adjustedLabelSize.height;
}
else {
    CGSize adjustedLabelSize = [string sizeWithFont:font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];

    return adjustedLabelSize.height;
}

}
于 2014-01-17T14:55:06.537 に答える
-2

iOS7に合わせたアップデート

// If description are available for protocol
protocolDescriptionLabel.text = [dataDictionary objectForKey:@"description"];
[protocolDescriptionLabel sizeToFit];
[protocolDescriptionLabel setLineBreakMode:NSLineBreakByWordWrapping];

CGSize expectedLabelSize = [protocolDescriptionLabel
               textRectForBounds:protocolDescriptionLabel.frame
               limitedToNumberOfLines:protocolDescriptionLabel.numberOfLines].size;
NSLog(@"expectedLabelSize %f", expectedLabelSize.height);

//adjust the label the the new height.
CGRect newFrame = protocolDescriptionLabel.frame;
newFrame.size.height = expectedLabelSize.height;
protocolDescriptionLabel.frame = newFrame;
于 2013-11-13T07:51:19.247 に答える