programing

텍스트에 따라 UI 레이블 높이 조정

mailnote 2023. 5. 16. 22:52
반응형

텍스트에 따라 UI 레이블 높이 조정

다음 텍스트가 있다고 생각합니다.UILabel(동적 텍스트의 긴 줄):

외계인 군대가 팀을 훨씬 능가하기 때문에, 플레이어는 쓰레기통, 기둥, 자동차, 잔해 및 다른 물체 뒤로 숨는 것과 같은 종말론적 세계를 자신들에게 유리하게 사용해야 합니다.

는 조정다니합크의 를 조정하고 .UILabel's텍스트가 들어갈 수 있도록 높이를 지정합니다.다음 속성을 사용하고 있습니다.UILabel텍스트를 랩으로 만듭니다.

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

제가 잘못된 방향으로 가고 있다면 알려주세요.감사해요.

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;

당신은 올바른 방향으로 가고 있었습니다.필요한 것은 다음과 같습니다.

myUILabel.numberOfLines = 0;
myUILabel.text = @"Enter large amount of text here";
[myUILabel sizeToFit];

iOS 6에서 Apple은 UILabel에 레이블의 동적 수직 크기 조정을 크게 단순화하는 속성인 선호 MaxLayoutWidth를 추가했습니다.

lineBreakMode = NSLineBreakByWordWrapingsizeToFit 메서드와 함께 이 속성을 사용하면 UI 레이블 인스턴스의 크기를 전체 텍스트를 수용하는 높이로 쉽게 조정할 수 있습니다.

iOS 설명서의 인용문:

preferredMaxLayoutWidth 다중선 레이블에 대해 선호되는 최대 너비(포인트 단위).

토론 이 속성은 레이아웃 제약 조건이 적용될 때 레이블의 크기에 영향을 미칩니다.레이아웃 중에 텍스트가 이 속성에서 지정한 너비를 초과하면 추가 텍스트가 하나 이상의 새 줄로 흐르게 되므로 레이블의 높이가 증가합니다.

샘플:

...
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];
...

코드 한 줄을 추가하지 않고 이 작업을 완벽하게 확인합니다.(자동 레이아웃 사용)

저는 당신의 요구에 따라 당신을 위해 데모를 만들었습니다.아래 링크에서 다운로드하십시오.

UIView 및 UI 레이블 자동 크기 조정

단계별 가이드:-

1단계:- 구속조건을 UIView로 설정

선행 2) 상위 3) 후행(메인 뷰에서)

여기에 이미지 설명 입력

2단계 : - 구속조건을 라벨 1로 설정

선행 2) 상위 3) 후행(수퍼뷰에서)

여기에 이미지 설명 입력

3단계 : - 구속조건을 라벨 2로 설정

선행 2) 트레일링(수퍼뷰에서)

여기에 이미지 설명 입력

4단계 :- 가장 까다로운 것은 UIView에서 UILabel에게 버튼을 주는 입니다.

여기에 이미지 설명 입력

5단계 : - (선택사항) 구속조건을 UIButton으로 설정

선행 2) 하단 3) 후행 4) 고정 높이(메인 뷰에서)

여기에 이미지 설명 입력

출력 :-

여기에 이미지 설명 입력

참고:- Label 속성에서 줄 수 = 0을 설정했는지 확인합니다.

여기에 이미지 설명 입력

나는 이 정보가 UILabel의 높이에 따른 자동 크기 UIView와 텍스트에 따른 자동 크기 UILabel을 충분히 이해할 수 있기를 바랍니다.

프로그래밍 방식으로 이 작업을 수행하는 대신 Storyboard/X에서 이 작업을 수행할 수 있습니다.설계 중 IB.

  • 특성 검사기에서 UIlabel의 줄 속성을 0으로 설정합니다.
  • 그런 다음 요구 사항에 따라 폭 제약 조건/(또는) 선행 및 후행 제약 조건을 설정합니다.
  • 그런 다음 높이 제약 조건을 최소값으로 설정합니다.마지막으로 추가한 높이 제약 조건을 선택하고 크기 검사기에서 특성 검사기 옆에 있는 것을 선택합니다. 높이 제약 조건의 관계동일에서 - 보다 큼으로 변경합니다.

여러분, 도와주셔서 감사합니다. 여기 제가 시도한 코드가 있습니다.

   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];

iOS7 이전 버전 및 iOS7 위 버전에 대한 솔루션

//
//  UILabel+DynamicHeight.m
//  For StackOverFlow
//
//  Created by Vijay on 24/02/14.
//  Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//

#import <UIKit/UIKit.h>

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

#define iOS7_0 @"7.0"

@interface UILabel (DynamicHeight)

/*====================================================================*/

/* Calculate the size,bounds,frame of the Multi line Label */

/*====================================================================*/
/**
 *  Returns the size of the Label
 *
 *  @param aLabel To be used to calculte the height
 *
 *  @return size of the Label
 */

-(CGSize)sizeOfMultiLineLabel;

@end


//
//  UILabel+DynamicHeight.m
//  For StackOverFlow
//
//  Created by Vijay on 24/02/14.
//  Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//

#import "UILabel+DynamicHeight.h"

@implementation UILabel (DynamicHeight)
/*====================================================================*/

/* Calculate the size,bounds,frame of the Multi line Label */

/*====================================================================*/
/**
 *  Returns the size of the Label
 *
 *  @param aLabel To be used to calculte the height
 *
 *  @return size of the Label
 */
-(CGSize)sizeOfMultiLineLabel{

    NSAssert(self, @"UILabel was nil");

    //Label text
    NSString *aLabelTextString = [self text];

    //Label font
    UIFont *aLabelFont = [self font];

    //Width of the Label
    CGFloat aLabelSizeWidth = self.frame.size.width;


    if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
        //version < 7.0

        return [aLabelTextString sizeWithFont:aLabelFont
                            constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                lineBreakMode:NSLineBreakByWordWrapping];
    }
    else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
        //version >= 7.0

        //Return the calculated size of the Label
        return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{
                                                        NSFontAttributeName : aLabelFont
                                                        }
                                              context:nil].size;

    }

    return [self bounds].size;

}

@end

크기 이후폰트가 사용되지 않는 경우에는 이 폰트를 대신 사용합니다.

레이블별 특성을 가져옵니다.

-(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);
}

Swift 4 이상에 대한답변을 기반으로 한 UI 레이블 확장

extension UILabel {

    func retrieveTextHeight () -> CGFloat {
        let attributedText = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:self.font])

        let rect = attributedText.boundingRect(with: CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

        return ceil(rect.size.height)
    }

}

다음과 같이 사용할 수 있습니다.

self.labelHeightConstraint.constant = self.label.retrieveTextHeight()

카테고리 버전은 다음과 같습니다.

UILabel+AutoSize.h #가져오기

@interface UILabel (AutoSize)

- (void) autosizeForWidth: (int) width;

@end

UILabel+자동 크기.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

은 수있다니습을 구현할 수 .TableViewController's (UITableViewCell *)tableView:cellForRowAtIndexPath과 같습니다 "methodice_1(예:

#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:텍스트 높이를 계산하는 방법입니다.

UI 레이블의 동적 높이를 계산하는 나의 접근 방식.

    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
}

iOS 8로 마이그레이션하는 사용자를 위해 Swift의 클래스 확장은 다음과 같습니다.

extension UILabel {

    func autoresize() {
        if let textNSString: NSString = self.text {
            let rect = textNSString.boundingRectWithSize(CGSizeMake(self.frame.size.width, CGFloat.max),
                options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                attributes: [NSFontAttributeName: self.font],
                context: nil)
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, rect.height)
        }
    }

}

제게 가장 쉽고 좋은 방법은 레이블에 높이 제한을 적용하고 스토리보드에서 우선순위를 낮음(250)으로 설정하는 것이었습니다.

따라서 스토리보드 덕분에 프로그래밍 방식으로 높이와 너비를 계산할 필요가 없습니다.

업데이트된 방법

+ (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;
}

다음은 목표-c를 사용하여 UI 레이블 높이를 가져오는 코드 한 줄입니다.

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

그리고 .height를 사용하면 다음과 같이 레이블의 높이를 얻을 수 있습니다.

neededSize.height

아래 코드를 사용하여 높이를 얻을 수 있습니다.

합격해야 합니다.

  1. 텍스트 2. 글꼴 3. 레이블 너비

    func heightForLabel(text: String, font: UIFont, width: CGFloat) -> CGFloat {
    
       let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
       label.numberOfLines = 0
       label.lineBreakMode = NSLineBreakMode.byWordWrapping
       label.font = font
       label.text = text
       label.sizeToFit()
    
       return label.frame.height
    }
    

이 게시물을 보내주셔서 감사합니다.그것은 저에게 큰 도움이 되었습니다.저의 경우에는 별도의 보기 컨트롤러에서 텍스트를 편집하고 있습니다.다음을 사용할 때 확인할 수 있었습니다.

[cell.contentView addSubview:cellLabel];

셀을 편집할 때마다 레이블 뷰가 이전 뷰의 맨 위에 연속적으로 렌더링되는 보기:cellForRowAtIndexPath:method입니다.텍스트가 픽셀화되어 삭제되거나 변경되면 이전 버전이 새 버전 아래에 표시됩니다.문제를 해결한 방법은 다음과 같습니다.

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

더 이상 이상 이상한 계층화는 없습니다.더 좋은 방법이 있다면 알려주시기 바랍니다.

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 = @"diofgorigjveghnhkvjteinughntivugenvitugnvkejrfgnvkhv";

필요에 따라 Perfetc 답변을 보여줍니다.

방법으로도 사용할 수 있습니다.@파자마삼은 매우 사실이기 때문에 그 방법을 만드는 중입니다.다른 사람에게 도움이 될 수 있습니다.

-(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];

Swift3에서 이 작업을 수행하려면 다음과 같은 코드가 있습니다.

 let labelSizeWithFixedWith = CGSize(width: 300, height: CGFloat.greatestFiniteMagnitude)
            let exactLabelsize = self.label.sizeThatFits(labelSizeWithFixedWith)
            self.label.frame = CGRect(origin: CGPoint(x: 20, y: 20), size: exactLabelsize)

위의 답변에 추가:

이는 스토리보드를 통해 쉽게 달성할 수 있습니다.

  1. UI 레이블에 대한 제약 조건을 설정합니다.(저의 경우 상단, 왼쪽, 고정 폭을 사용했습니다.)
  2. 특성 검사기에서 줄 를 0으로 설정
  3. 속성 관리자에서 줄 바꿈을 WordWrap으로 설정합니다.

UI 레이블 높이 조정

한 줄은 크리스의 대답이 틀렸다는 것입니다.

newFrame.size.height = maximumLabelSize.height;

그래야 한다

newFrame.size.height = expectedLabelSize.height;

그 외에는 올바른 해결책입니다.

마침내, 효과가 있었습니다.감사합니다.

라벨 크기를 조정하려고 했기 때문에 작동하지 않았습니다.heightForRowAtIndexPath방법:

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

그리고 (네 바보 같은 나), 나는 라벨의 크기를 기본값으로 조정하고 있었습니다.cellForRowAtIndexPath방법 - 나는 내가 이전에 작성한 코드를 간과하고 있었습니다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
-(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;    
}
NSString *str = @"Please enter your text......";
CGSize lblSize = [str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize: CGSizeMake(200.0f, 600.0f) lineBreakMode: NSLineBreakByWordWrapping];

UILabel *label = [[UILabel alloc]init];
label.frame = CGRectMake(60, 20, 200, lblSize.height);
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.font = [UIFont systemFontOfSize:15];
label.text = str;
label.backgroundColor = [UIColor clearColor];
[label sizeToFit];
[self.view addSubview:label];

내 코드:

UILabel *label      = [[UILabel alloc] init];
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.text          = text;
label.textAlignment = NSTextAlignmentCenter;
label.font          = [UIFont fontWithName:_bodyTextFontFamily size:_bodyFontSize];

CGSize size = [label sizeThatFits:CGSizeMake(width, MAXFLOAT)];


float height        = size.height;
label.frame         = CGRectMake(x, y, width, height);

이 방법은 완벽한 높이를 제공합니다.

-(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;
}

스위프트 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()

흥미로운 대사는sizeToFit()a를 설정하는frame.size.height최대 플로트까지, 이것은 긴 텍스트를 위한 공간을 줄 것이지만,sizeToFit()필요한 것만 사용하도록 강제하지만 항상 설정한 후에 호출합니다..frame.size.height.

설정할 것을 권장합니다..backgroundColor디버그 목적을 위해, 이 방법으로 각 사례에 대해 렌더링되는 프레임을 볼 수 있습니다.

myLabel.text = "your very long text"
myLabel.numberOfLines = 0
myLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

왼쪽 상단 오른쪽 하단을 포함하여 스토리보드에서 UILable에 대한 제약 조건을 설정하십시오.

언급URL : https://stackoverflow.com/questions/446405/adjust-uilabel-height-depending-on-the-text

반응형