Tag Archives: iPhone SDK

[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

[iPhone] Object-C : Categories

Objective C를 사용하다 보니 매우 특이한점이 하나 있습니다. 제 생각에는 그 어떤 언어에서도 보기 힘든 모습이 아닐까 싶네요.

굳이 비교를 해보자면 Javascript같은 느낌이랄까요. 그게 무엇이냐 하면 바로 Category입니다.

보통은 특정 클래스에 메서드를 추가하기 위해서는 해당 클래스를 상속받은 이후에 그 상속받아 구현한 클래스를 사용하는것이 일반적인 객체 지향입니다.

그런데 Objective C에 있는 Category라는 개념을 사용하면 기존의 클래스에 내가 구현한 메서드를 추가할 수 있습니다.

그래서 결과적으로 기존의 소스코드에 크게 더럽히지 않고 각각의 클래스들의 기능을 확장 할 수 있습니다.

[code]#import “NSString+Dollar.h”
#import “NSString+Won.h”

– (void)applicationDidFinishLaunching:(UIApplication *)application
{
    NSString *string = @”100″;
   
    NSLog(@”%@”, [string stringWithDollar]);
    NSLog(@”%@”, [string stringWithWon]);
   
    [window makeKeyAndVisible];
}[/code]
NSString+Dollar.h
[code]#import <Foundation/Foundation.h>

@interface NSString (Dollar)

– (NSString *)stringWithDollar;

@end[/code]
NSString+Dollar.m
[code]#import “NSString+Dollar.h”

@implementation NSString (Dollar)

– (NSString *)stringWithDollar
{
    return [NSString stringWithFormat:@”$%@”, self];
}

@end[/code]
NSString+Won.h
[code]#import <Foundation/Foundation.h>

@interface NSString (Won)

– (NSString *)stringWithWon;

@end[/code]
NSString+Won.m
[code]#import “NSString+Won.h”

@implementation NSString (Won)

– (NSString *)stringWithWon
{
    return [NSString stringWithFormat:@”%@원”, self];
}

@end[/code]
사용자 삽입 이미지기본적으로 Category를 정의하는 클래스들의 파일명은 기존클래스명+추가기능으로 합니다.

보시면 아시겠지만 @interface에 괄호()가 들어가며 그 안에는 별칭(Alias)이 들어가게 됩니다.

여기서 보시면 @interface 구현부에 맴버 변수가 정의되는 중괄호{}가 없는걸 아실 수 있습니다.

이와 같은 기능을 사용하여 매우 간편하게 클래스들을 확장할 수 있습니다. 실제로 JSON관련 라이브러리들을 보면 NSDictionary를 확장하고 있습니다.
1058497054.zip