簡體   English   中英

如何根據iOS中的內容更改UILabel高度

[英]How to change UILabel height according to content in iOS

我在動態標簽高度上遇到問題。我的要求如下圖所示:

在此處輸入圖片說明

我正在使用UIScrollView並在UIScrollView添加了UILabel以顯示內容。 我的內容是不同類型的文本大小。 如果我將1個內容設置為完美,但是如果我將內容放置在Array中,則它如下圖所示:

在此處輸入圖片說明

有6種內容,其文字大小不同。 我實現了這種類型:

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 42, SCREEN_WIDTH, SCREEN_HEIGHT - 152)];
[scroll setBackgroundColor:[UIColor clearColor]];
[scroll setContentOffset:CGPointMake(0, 0)];
[scroll setShowsHorizontalScrollIndicator:NO];
[scroll setShowsVerticalScrollIndicator:NO];
[self.view addSubview:scroll];

contentArr = [[NSArray alloc] initWithObjects:@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla",@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ",@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu",@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla",@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et ", nil];


float x_pos = 5;
float y_pos = 5;

for (int i = 0; i < contentArr.count; i ++)
{
    NSString *text1 = [contentArr objectAtIndex:i];
    CGSize constraint1 = CGSizeMake(152.5, 2000);
    CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];

    NSLog(@"size1.height == %f",size1.height);

    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(x_pos,y_pos,152.5,size1.height)];
    bgView.backgroundColor = APP_BGCOLOR;
    [scroll addSubview:bgView];

    [bgView.layer setBorderColor:[[UIColor colorWithRed:(170.0 / 255.0) green:(170.0 / 255.0) blue:(170.0 / 255.0) alpha:0.5] CGColor]];
    [bgView.layer setBorderWidth:1.0f];
    bgView.layer.cornerRadius = 4.0;
    bgView.layer.masksToBounds = YES;

    UILabel *lblComment = [[UILabel alloc] initWithFrame:CGRectMake(7,20,bgView.frame.size.width -14,bgView.frame.size.height - 20)] ;
    [lblComment setLineBreakMode:NSLineBreakByWordWrapping];
    lblComment.numberOfLines = size1.height/15;
    [lblComment setFont:[UIFont systemFontOfSize:10]];
    lblComment.text = text1;
    lblComment.backgroundColor = [UIColor clearColor];
    lblComment.tag = 1;
    [lblComment setNeedsDisplay];
    [bgView addSubview:lblComment];

    x_pos = x_pos + 157.5;

    if (x_pos > 300)
    {
        x_pos = 5;
        y_pos = y_pos + size1.height + 10;
    }

    [scroll setContentSize:CGSizeMake(SCREEN_WIDTH, y_pos)];
}

如果我只接受1個內容並在For循環之前編寫用於動態文本高度的代碼,則其效果將類似於2nd Image。

我正在遵循以下代碼:

NSString *text1 = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";

CGSize constraint1 = CGSizeMake(152.5, 2000);
CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];

如何解決這個問題?

如果有任何想法,請建議我...

有幾種方法可以做到這一點:

#1計算textSize然后設置為label:

- (CGSize)calculateSizeWithNSString:(NSString *)str {
  CGSize constraint1 = CGSizeMake(LABEL_WIDTH, FLT_MAX);
  UIFont *font = [UIFont systemFontOfSize:12];
  NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
  paragraph.lineBreakMode = NSLineBreakByWordWrapping;

  NSDictionary *attributesDictionary = [NSDictionary
      dictionaryWithObjectsAndKeys:font, NSFontAttributeName, paragraph,
                                   NSParagraphStyleAttributeName, nil];
  if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
  CGRect rect = [str boundingRectWithSize:constraint1
                             options:(NSStringDrawingUsesLineFragmentOrigin |
                                      NSStringDrawingUsesFontLeading)
                          attributes:attributesDictionary
                             context:nil];
    constraint1 = rect.size;
  } else {
        //sizeWithFont:constrainedToSize:lineBreakMode: was deprecated from iOS7.0
        constraint1 = [str sizeWithFont:font
                      constrainedToSize:constraint1
                          lineBreakMode:NSLineBreakByWordWrapping];
      }
      return constraint1;
    }

#2將文本設置為標簽,然后使用sizeThatFit:方法計算真實大小的約束:

- (void)changeLabelSize:(UILabel *)label {
  CGRect labelFrame = label.frame;
  CGSize constraint1 = CGSizeMake(LABEL_WIDTH, FLT_MAX);
  CGSize expectSize = [label sizeThatFits:constraint1];
  labelFrame.size = expectSize;
  label.frame = labelFrame;
}

我認為在這種情況下, sizeThatFits:[label sizeToFit]是更好的選擇,因為您想提供一個尺寸(列寬)作為參數:(非常感謝傑夫糾正我)

蘋果文件

#EDIT:使用方法2:

//.....
 // remove this line you dont need it any more
 CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];
//...
[lblComment setFont:[UIFont systemFontOfSize:10]];
    lblComment.text = text1;
[self changeLabelSize:lblComment];
CGSize size1 = lblComment.frame.size; //for your calculate x_pos, y_pos code
[bgView addSubview:lblComment];
//....

編輯2:x_pos,y_pos計算

我有一個計算x_pos,y_pos的想法

    float col1_y_pos = 5;
    float col2_y_pos = 5;
    for (int i = 0; i < contentArr.count; i ++)
    {
        BOOL isColumn1 = (i%2 == 0)
        float x_pos = isColumn1 ? 5 : column2_x_pos_value;
        float y_pos = isColumn1 ? col1_y_pos: col2_y_pos;
        //your code set label frame with x_pos, y_pos
        //....
        CGSize size1 = lblComment.frame.size; 
        [bgView addSubview:lblComment];
        if (isColumn1) { 
           col1_y_pos += size1.height + marginTop;
        } else {
          col2_y_pos += size1.height + marginTop;
        }
   //....

您的文本有兩列。 每行中的標簽高度不同,您只有1個浮點y_pos來設置標簽位置。 如果您看到第一列中的每個label都被放置為與第二列標簽相等,則僅是因為您根據第二列維護y_pos 您需要維護y_posLeft y_posRight

 float x_pos = 5;
    float y_posLeft = 5;
    float y_posRight = 5;

    for (int i = 0; i < contentArr.count; i ++)
    {
        NSString *text1 = [contentArr objectAtIndex:i];

//        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(x_pos,y_pos,152.5,9999)];
//        bgView.backgroundColor = [UIColor lightGrayColor];
//        [scroll addSubview:bgView];

        UILabel *lblComment = [[UILabel alloc] initWithFrame:CGRectMake(x_pos, (i%2 == 1)?y_posRight:y_posLeft, 152.5, 1999)] ;
        [lblComment setLineBreakMode:NSLineBreakByWordWrapping];
        lblComment.numberOfLines = 0;
        [lblComment setFont:[UIFont systemFontOfSize:10]];
        lblComment.backgroundColor = [UIColor whiteColor];
        lblComment.text = text1;
        [self changeLabelSize:lblComment];
        CGSize size1 = lblComment.frame.size;
        [scroll addSubview:lblComment];

        [lblComment.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
        [lblComment.layer setBorderWidth:1.0f];
        lblComment.layer.cornerRadius = 4.0;
        lblComment.layer.masksToBounds = YES;
        if (x_pos == 5)
        {
            y_posLeft = y_posLeft + size1.height + 10;
        }
        else
        {
            y_posRight = y_posRight + size1.height + 10;
        }

        x_pos = x_pos + 157.5;

        if (x_pos > 300)
        {
            x_pos = 5;
        }


        [scroll setContentSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width, MAX(y_posLeft, y_posRight))];
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM