[iPhone] 컨텐츠의 사이즈에 맞추어 UILabel 크기 변경하기

기존의 글에서 UILabel을 이용하여 컨텐츠를 보여주는 다양한 방법에 대해 이야기 하였습니다.

두줄 이상을 표시하기
문자열 크기에 맞추어 UILabel frame 크기 변경하기

하지만 위의 링크에서 두번째 글의 경우에는 특정한 상황에서 매우 비정상적인 결과를 보여줍니다.

방법을 찾다 보니 sizeWithFont 메서드가 문제가 있는 메서드이더군요.

다음의 방법을 사용하는것이 가장 확실한 방법인듯 합니다.

[code]- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    NSString *string = @”I have a very beautiful girl-friend. but she is not love me after last weekend.\nI love her”;
   
    UIFont *stringFont = [UIFont boldSystemFontOfSize:15.0f];
    CGSize stringSize = [string sizeWithFont:stringFont constrainedToSize:CGSizeMake(280.0f, 60.0f) lineBreakMode:UILineBreakModeWordWrap];
   
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 50.0f, stringSize.width, stringSize.height)];
    [label setFont:stringFont];
    [label setText:string];
    [label setNumberOfLines:0];
    [label setLineBreakMode:UILineBreakModeWordWrap];
   
    [window addSubview:label];
    [label release];
   
    [window setBackgroundColor:[UIColor blackColor]];
    [window makeKeyAndVisible];
}[/code]

바로 sizeWithFont:constrainedToSize:lineBreakMode 를 사용하는 것인데요. 가장 좋은 결과를 보여주더군요.
사용자 삽입 이미지constrainedToSize에서 정의한 크기가 최대 제한 사이즈가 되며 그것을 넘어가게 되면 자동으로 줄바꿈이 일어납니다.
1393999463.zip