programing

텍스트 길이를 기준으로 UILabel 너비를 계산하는 방법은 무엇입니까?

jooyons 2023. 4. 20. 21:11
반응형

텍스트 길이를 기준으로 UILabel 너비를 계산하는 방법은 무엇입니까?

UILabel 옆에 이미지를 표시하고 싶은데, UILabel의 텍스트 길이가 다양하기 때문에 이미지를 어디에 배치해야 할지 모르겠습니다.어떻게 하면 좋을까요?

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

[NSString sizeWithFont:forWidth:lineBreakMode:]의 장점은 무엇입니까?

이 질문에 답이 있을 수도 있어, 나한테는 효과가 있었어.


2014년에는 아래 Norbert의 초핸디 코멘트를 바탕으로 편집했습니다!이게 모든 걸 할 수 있어.

// yourLabel is your UILabel.

float widthIs = 
 [self.yourLabel.text
  boundingRectWithSize:self.yourLabel.frame.size                                           
  options:NSStringDrawingUsesLineFragmentOrigin
  attributes:@{ NSFontAttributeName:self.yourLabel.font }
  context:nil]
   .size.width;

NSLog(@"the width of yourLabel is %f", widthIs);

yourLabel.intrinsicContentSize.widthObjective-C/Swift의 경우

재빠르게

 yourLabel.intrinsicContentSize().width 

선택한 답변은 iOS 6 이하에서 정답입니다.

iOS 7에서는sizeWithFont:constrainedToSize:lineBreakMode:는 폐지되었습니다.이제 다음을 사용하는 것이 좋습니다.boundingRectWithSize:options:attributes:context:.

CGRect expectedLabelSize = [yourString boundingRectWithSize:sizeOfRect
                                                    options:<NSStringDrawingOptions>
                                                 attributes:@{
                                                    NSFontAttributeName: yourString.font
                                                    AnyOtherAttributes: valuesForAttributes
                                                 }
                                                    context:(NSStringDrawingContext *)];

반환값은 다음과 같습니다.CGRect단 한 명도 없다CGSizeiOS 7에서 사용하는 사람들에게 도움이 되었으면 합니다.

구속조건을 사용하는 Swift 4 답변

label.text = "Hello World"

var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(attributes: [NSFontAttributeName: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet

구속조건을 사용하는 Swift 5 답변

label.text = "Hello World"

var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(withAttributes: [NSAttributedString.Key.font: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet

iOS8 사이즈WithFont는 폐지되었습니다.를 참조해 주세요.

CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];

원하는 모든 속성을 크기에 추가할 수 있습니다.With Attributes(속성 포함)설정할 수 있는 기타 속성:

- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName

기타 등등.하지만 아마 다른 것들은 필요 없을 거야

CGRect rect = label.frame;
rect.size = [label.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:label.font.fontName size:label.font.pointSize]}];
label.frame = rect;

다음은 Aaron의 링크를 포함한 다른 SO 포스트의 몇 가지 원칙을 적용한 후 생각해 낸 것입니다.

AnnotationPin *myAnnotation = (AnnotationPin *)annotation;

self = [super initWithAnnotation:myAnnotation reuseIdentifier:reuseIdentifier];
self.backgroundColor = [UIColor greenColor];
self.frame = CGRectMake(0,0,30,30);
imageView = [[UIImageView alloc] initWithImage:myAnnotation.THEIMAGE];
imageView.frame = CGRectMake(3,3,20,20);
imageView.layer.masksToBounds = NO;
[self addSubview:imageView];
[imageView release];

CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]];
CGRect newFrame = self.frame;
newFrame.size.height = titleSize.height + 12;
newFrame.size.width = titleSize.width + 32;
self.frame = newFrame;
self.layer.borderColor = [UIColor colorWithRed:0 green:.3 blue:0 alpha:1.0f].CGColor;
self.layer.borderWidth = 3.0;
        
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(26,5,newFrame.size.width-32,newFrame.size.height-12)];
infoLabel.text = myAnnotation.title;
infoLabel.backgroundColor = [UIColor clearColor];
infoLabel.textColor = [UIColor blackColor];
infoLabel.textAlignment = UITextAlignmentCenter;
infoLabel.font = [UIFont systemFontOfSize:12];

[self addSubview:infoLabel];
[infoLabel release];

이 예에서는 텍스트 크기에 따라 UILabel 크기를 조정하는 MKAnnotation 클래스에 사용자 지정 핀을 추가합니다.또한 보기 왼쪽에 이미지가 추가되므로 일부 코드가 이미지 및 패딩을 처리하기 위해 적절한 간격을 관리하고 있습니다.

중요한 것은,CGSize titleSize = [myAnnotation.THETEXT sizeWithFont:[UIFont systemFontOfSize:12]];뷰의 치수를 다시 정의합니다.이 논리는 모든 보기에 적용할 수 있습니다.

애런의 대답은 어떤 사람들에게는 먹히지만, 나에게는 먹히지 않았다.이미지 및 크기 조정 가능한 UILabel을 사용하여 보다 역동적인 보기를 원하는 경우 다른 곳으로 이동하기 전에 바로 시도해야 하는 훨씬 자세한 설명입니다.난 이미 널 위해 모든 일을 했어!!

언급URL : https://stackoverflow.com/questions/3527494/how-to-calculate-uilabel-width-based-on-text-length

반응형