Programing

UILabel-텍스트에 맞게 자동 크기 레이블?

lottogame 2020. 6. 17. 20:28
반응형

UILabel-텍스트에 맞게 자동 크기 레이블?


포함 된 텍스트에 맞게 UILabel 상자 / 바운드의 크기를 자동으로 조정할 수 있습니까? (디스플레이보다 큰 경우에는 신경 쓰지 않습니다)

따라서 사용자가 "hello"를 입력하거나 "내 이름이 정말로 길어서이 상자에 맞추기를 원합니다"라고하면 절대 잘리지 않으며 레이블이 '확대'됩니다.


UILabel매우 비슷한 것을 위해 카테고리를 만든 곳에서 요점을 확인하십시오 . 내 카테고리는 UILabel모든 내용을 보여주기 위해 높이를 늘릴 수 있습니다 : https://gist.github.com/1005520

또는이 게시물을 확인하십시오 : https://stackoverflow.com/a/7242981/662605

이것은 높이를 늘릴 것이지만 다른 방법으로 작업하기 위해 쉽게 바꿀 수 있으며 다음과 같이 너비를 늘릴 수 있습니다.

@implementation UILabel (dynamicSizeMeWidth)

- (void)resizeToStretch{
    float width = [self expectedWidth];
    CGRect newFrame = [self frame];
    newFrame.size.width = width;
    [self setFrame:newFrame];
}

- (float)expectedWidth{
    [self setNumberOfLines:1];

    CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);

    CGSize expectedLabelSize = [[self text] sizeWithFont:[self font] 
                                            constrainedToSize:maximumLabelSize
                                            lineBreakMode:[self lineBreakMode]]; 
    return expectedLabelSize.width;
}

@end

클래스 sizeToFit에서 사용할 수 있는 메소드를 더 간단하게 사용할 UIView있지만 행 수를 1로 설정하여 안전합니다.


iOS 6 업데이트

자동 레이아웃을 사용하는 경우 기본 제공 솔루션이 있습니다. 줄 수를 0으로 설정하면 프레임 워크가 텍스트에 맞게 레이블의 크기를 적절하게 조정합니다 (높이 추가).


iOS 8 업데이트

sizeWithFont:더 이상 사용되지 않으므로 sizeWithAttributes:대신 사용하십시오.

- (float)expectedWidth{
    [self setNumberOfLines:1];

    CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];

    return expectedLabelSize.width;
}

를 사용 [label sizeToFit];하면 Daniels 카테고리에서 동일한 결과를 얻을 수 있습니다.

자동 레이아웃을 사용하고 제약 조건에 따라 레이블 크기를 조정하는 것이 좋습니다.


우리가 원하는 경우 UILabel다음 자동 레이아웃과 스토리 보드 텍스트 크기에 따라 축소 및 확대해야 최선의 방법입니다. 이를 달성하기위한 단계는 다음과 같습니다.

단계

  1. UILabel을 뷰 컨트롤러에 넣고 원하는 위치에 배치하십시오. 또한 넣어 0위해 numberOfLines의 특성 UILabel.

  2. 상단, 선행 및 후행 공간 핀 구속 조건을 지정하십시오.

여기에 이미지 설명을 입력하십시오

  1. 이제 경고가 나타납니다. 노란색 화살표를 클릭하십시오.

여기에 이미지 설명을 입력하십시오

  1. 를 클릭 Update Frame하고를 클릭하십시오 Fix Misplacement. 이제이 UILabel은 텍스트가 적 으면 축소되고 텍스트가 많으면 확장됩니다.

이것은 다른 답변 중 일부만큼 복잡하지 않습니다.

여기에 이미지 설명을 입력하십시오

왼쪽과 위쪽 가장자리를 고정

자동 레이아웃을 사용하여 라벨의 왼쪽과 상단을 고정하는 구속 조건을 추가하십시오.

여기에 이미지 설명을 입력하십시오

그 후 자동으로 크기가 조정됩니다.

노트

  • 너비와 높이에 대한 구속 조건을 추가하지 마십시오. 레이블은 텍스트 내용에 따라 고유 한 크기를 갖습니다 .
  • 이에 대한 도움을 주신이 답변감사드립니다 .
  • No need to set sizeToFit when using auto layout. My complete code for the example project is here:

    import UIKit
    class ViewController: UIViewController {
    
        @IBOutlet weak var myLabel: UILabel!
    
        @IBAction func changeTextButtonTapped(sender: UIButton) {
            myLabel.text = "my name is really long i want it to fit in this box"
        }
    }
    
  • If you want your label to line wrap then set the number of lines to 0 in IB and add myLabel.preferredMaxLayoutWidth = 150 // or whatever in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)

여기에 이미지 설명을 입력하십시오

  • If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.

여기에 이미지 설명을 입력하십시오


Use [label sizeToFit]; to adjust the text in UILabel


I created some methods based Daniel's reply above.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
    CGSize maximumLabelSize     = CGSizeMake(290, FLT_MAX);

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

    return expectedLabelSize.height;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label
{
    CGRect newFrame         = label.frame;
    newFrame.size.height    = [self heightForLabel:label withText:label.text];
    label.frame             = newFrame;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
    label.text              = text;
    [self resizeHeightToFitForLabel:label];
}

@implementation UILabel (UILabel_Auto)

- (void)adjustHeight {

    if (self.text == nil) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
        return;
    }

    CGSize aSize = self.bounds.size;
    CGSize tmpSize = CGRectInfinite.size;
    tmpSize.width = aSize.width;

    tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}

@end

This is category method. You must set text first, than call this method to adjust UILabel's height.


You can size your label according to text and other related controls using two ways-

  1. For iOS 7.0 and above

    CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{
                                                        NSFontAttributeName : labelFont
                                                        }
                                              context:nil].size;
    

before iOS 7.0 this could be used to calculate label size

CGSize labelTextSize = [label.text sizeWithFont:label.font 
                            constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)  
                                lineBreakMode:NSLineBreakByWordWrapping];

// reframe other controls based on labelTextHeight

CGFloat labelTextHeight = labelTextSize.height;
  1. If you do not want to calculate the size of the label's text than you can use -sizeToFit on the instance of UILabel as-

    [label setNumberOfLines:0]; // for multiline label
    [label setText:@"label text to set"];
    [label sizeToFit];// call this to fit size of the label according to text
    

// after this you can get the label frame to reframe other related controls


  1. Add missing constraints in storyboard.
  2. Select UILabel in storyboard and set the attributes "Line" to 0.
  3. Ref Outlet the UILabel to Controller.h with id:label
  4. Controller.m and add [label sizeToFit]; in viewDidLoad

Here's what I am finding works for my situation:

1) The height of the UILabel has a >= 0 constraint using autolayout. The width is fixed. 2) Assign the text into the UILabel, which already has a superview at that point (not sure how vital that is). 3) Then, do:

    label.sizeToFit()
    label.layoutIfNeeded()

The height of the label is now set appropriately.


자동 레이아웃에 큰 문제가있었습니다. 테이블 셀 안에 두 개의 컨테이너가 있습니다. 두 번째 컨테이너는 항목 설명 (0-1000 자)에 따라 크기가 조정되며이를 기준으로 행의 크기를 조정해야합니다.

누락 된 성분은 설명에 대한 제약 조건이었습니다.

동적 요소의 하단 제약 조건을 = 0 에서 > = 0으로 변경했습니다 .


매번 적합합니다! :)

    name.text = @"Hi this the text I want to fit to"
    UIFont * font = 14.0f;
    CGSize size = [name.text sizeWithAttributes:@{NSFontAttributeName: font}];
    nameOfAssessment.frame = CGRectMake(400, 0, size.width, 44);
    nameOfAssessment.font = [UIFont systemFontOfSize:font];

한 줄 출력을 표시 한 다음 속성 Line = 0 을 설정 하고 여러 줄 출력을 표시 한 다음 속성 Line = 1 이상 을 설정할 수 있습니다

[self.yourLableName sizeToFit];

이 접근법도 있습니다.

[self.myLabel changeTextWithAutoHeight:self.myStringToAssignToLabel width:180.0f];

참고 URL : https://stackoverflow.com/questions/8796862/uilabel-auto-size-label-to-fit-text

반응형