code

표시 할 텍스트를 기준으로 UILabel 자동 크기 조정

codestyles 2021. 1. 5. 08:07
반응형

표시 할 텍스트를 기준으로 UILabel 자동 크기 조정


표시 할 텍스트를 기준으로 텍스트 영역의 크기를 자동으로 조정해야하는 응용 프로그램에서 작업 중입니다.

첫째, 나는 이것을 사용 해야하는지 UILabel(논리적으로 정적 텍스트를 표시하는 데 가장 적합한 선택이며, 내 경우에는) 또는 UITextView.

어떻게 사용하고 싶습니까?
텍스트로 해당 문제에 대한 레이블 또는 텍스트보기를 간단히 초기화하고 싶습니다. 대신 프레임을 먼저 정의한 다음 해당 영역에서 텍스트를 제한합니다.

올바른 솔루션을 제안 할 수 있다면 큰 도움이 될 것입니다.

문서 및 기타 참고 자료를 살펴 보았지만 여기서 도움이 될만한 내용을 많이 찾지 못했거나 간과 할 수있었습니다.


sizeToFit방법은 훌륭하게 작동했습니다.

나는 따라했다.

UILabel *testLabel =[[UILabel alloc] initWithFrame:CGRectMake(6,3, 262,20 )]; // RectMake(xPos,yPos,Max Width I want, is just a container value);

NSString * test=@"this is test this is test inthis is test ininthis is test inthis is test inthis is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...";

testLabel.text = test;
testLabel.numberOfLines = 0; //will wrap text in new line
[testLabel sizeToFit];

[self.view addSubview:testLabel];

다음을 사용하여 텍스트 크기를 찾을 수 있습니다.

CGSize textSize = [[myObject getALongText] 
                    sizeWithFont:[UIFont boldSystemFontOfSize:15] 
                    constrainedToSize:CGSizeMake(maxWidth, 2000)
                    lineBreakMode:UILineBreakModeWordWrap];

그런 다음 다음 UILabel과 같이 만들 수 있습니다 .

UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,textSize.width, textSize.height];
[lbl setNumberOfLines:0];
[lbl setLineBreakMode:UILineBreakModeWordWrap];
[lbl setText:[myObject getALongText]];

Swift에서 :

testLabel = UILabel(frame: CGRectMake(6, 3, 262, 20))
testLabel.text = test
testLabel.numberOfLines = 0
testLabel.sizeToFit()

목표 C에서

UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(6, 3, 262, 20)]];
testLabel.text = test;
testLabel.numberOfLines = 0;
[testLabel sizeToFit];

UILabel의 크기를 높이로만 조정하려면 다음을 사용하십시오.

@property (nonatomic, weak) IBOutlet UILabel *titleLabel;

CGRect titleLabelBounds = self.titleLabel.bounds;
titleLabelBounds.size.height = CGFLOAT_MAX;
// Change limitedToNumberOfLines to your preferred limit (0 for no limit)
CGRect minimumTextRect = [self.titleLabel textRectForBounds:titleLabelBounds limitedToNumberOfLines:2];

CGFloat titleLabelHeightDelta = minimumTextRect.size.height - self.titleLabel.frame.size.height;
CGRect titleFrame = self.titleLabel.frame;
titleFrame.size.height += titleLabelHeightDelta;
self.titleLabel.frame = titleFrame;

이제 titleLabelHeightDelta레이블 크기에 따라 다른 뷰를 레이아웃 하는 사용할 수 있습니다 (자동 레이아웃을 사용하지 않음).


나는 질문을 완전히 이해하고 있는지 잘 모르겠지만 레이블 텍스트에 따라 크기를 변경하기 위해 ( 에서 상속 된 메서드) sizeToFit메서드를 사용할 수 있습니다 .UILabelUIView


아니오를 찾는 가장 쉬운 방법. 텍스트에 따라 줄 수. 이 코드를 사용할 수 있습니다.

ceil(([aText sizeWithFont:aFont].width)/self.bounds.size.width-300); 

일부 부동 값을 반환합니다.

[lbl setNumberOfLines:floatvalue];

자동 레이아웃 호출을 사용하면 sizeToFit가 나중에 자동 레이아웃 계산에 의해 변경되므로 크기를 변경하지 않습니다. 이 경우 "height> = xx"값으로 UILabel에 적절한 높이 제약 조건을 설정해야합니다.


Because you're going to use this solution countless times in your app, do the following:

1) Create a directory called extensions and add a new file inside called UILabel.swift with the following code:

import UIKit

extension UILabel {
    func resizeToText() {
        self.numberOfLines = 0
        self.sizeToFit()
    }
}

2) In your app code, define the label width you want and just call resizeToText():

label.frame.size.width = labelWidth
label.resizeToText()

This will maintain width while increasing the height automatically.


try bellow code, it works for multiline

self.labelText.text = string;
self.labelText.lineBreakMode = NSLineBreakByWordWrapping;
self.labelText.numberOfLines = 0;

You can change the size of label based on length of the string by, using this function

func ChangeSizeOfLabel(text:String) -> CGSize{

    let font = UIFont(name: "HelveticaNeue", size: 12)!
    let textAttributes = [NSFontAttributeName: font]
    let size = text.boundingRectWithSize(CGSizeMake(310, 999), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
    let adjustSize = CGSizeMake(size.width, size.height)
    return adjustSize
}

and use it like this :

let

showLabel.frame = CGRectMake(x, y, width , self.ChangeSizeOfLabel("Hello , Height is changing dynamically.....").height)

ReferenceURL : https://stackoverflow.com/questions/5430890/uilabel-auto-resize-on-basis-of-text-to-be-shown

반응형