본문 바로가기

iPhone

[iOS] DEPRECATED iOS7 - sizeWithFont > boundingRectWithSize

Text처리에 필수적인

iOS7에서 Deprecated되어 있는 sizeWithFont: constrainedToSize: lineBreakMode: 의 대체방법에 대해 기록합니다.

@interface NSString(UIStringDrawing)

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:"); // Uses NSLineBreakModeWordWrap

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:"); // NSTextAlignment is not needed to determine size


@interface NSString (NSExtendedStringDrawing)

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(7_0);


아래 코드를 보면 쉽게 알 수 있습니다.

* 예제 -------------------------------------------------------------------------


    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];

    label.backgroundColor = [UIColor clearColor];

    label.textColor = [UIColor blackColor];

    label.font = [UIFont fontWithName:FONT_HELVETICANEUE size:15.0];

    label.text = @"Text가 들어가는 자리";

    label.textAlignment = TEXT_ALIGNMENT_LEFT;

    label.lineBreakMode = LINE_BREAK_WORD_WRAP;

    label.numberOfLines = 0;

    [veiw addSubview: label];

    ----------------------------------------------------------------------------------

    CGSize text_size = [label.text sizeWithFont: label.font constrainedToSize:CGSizeMake(320., 200.0) lineBreakMode: label.lineBreakMode];

    label.frame = CGRectMake(18.012.0, text_size.width, text_size.height);

    -----------------------------------------------------------------------------------

    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:

                                          label.font, NSFontAttributeName,

                                          label.textColor, NSForegroundColorAttributeName,

                                          nil];

    

    CGRect text_size = [label.text boundingRectWithSize:CGSizeMake(320., 200.0)

                                                            options:NSStringDrawingUsesLineFragmentOrigin //NSStringDrawingUsesFontLeading

                                                         attributes:attributesDictionary

                                                            context:nil];

    label.frame = CGRectMake(18.012.0, text_size.size.width, text_size.size.height);

    -----------------------------------------------------------------------------------


감사합니다.


* 참고사이트 : http://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size