'UILabel'에 해당되는 글 1건

  1. 2013.11.26 [iOS7] sizeWithFont:constrainedToSize:lineBreakMode
Programming/iOS2013.11.26 15:09

iOS7 으로 버전을 변경하여 빌드를 해보면  sizeWithFont:constrainedToSize:lineBreakMode 로 계산한 값들이 정확하지 않다는 것을 알 수 있다.

구글신의 도움으로 다음과 같은 방법으로 해결하였습니다.

아래 코드는 UILabel의 Category로 구현된 내용입니다.

- (CGSize)boundingSize:(CGSize)size
{
    CGSize resultSize;

#ifdef __IPHONE_7_0
    if ([self.text respondsToSelector:@selector(boundingRectWithSize:options:context:)]) {
        resultSize = [self.text boundingRectWithSize:size
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@{NSFontAttributeName:self.font}
                                             context:nil].size;
    }
    else {
#   pragma clang diagnostic push
#   pragma clang diagnostic ignored "-Wdeprecated-declarations"
        resultSize = [self.text sizeWithFont:self.font
                           constrainedToSize:size
                               lineBreakMode:NSLineBreakByWordWrapping];
#   pragma clang diagnostic pop
    }
#else
#   pragma clang diagnostic push
#   pragma clang diagnostic ignored "-Wdeprecated-declarations"
    resultSize = [self.text sizeWithFont:self.font
                       constrainedToSize:size
                           lineBreakMode:NSLineBreakByWordWrapping];
#   pragma clang diagnostic pop
#endif
    resultSize.width = ceil(resultSize.width);
    resultSize.height = ceil(resultSize.height);
    
    return resultSize;
}


NSString Category 구현


NSString+Size.h

#import 

@interface NSString (Size)

- (CGSize)boundingSize:(CGSize)size font:(UIFont*)font;

@end

NSString+Size.m
#import "NSString+Size.h"

@implementation NSString (Size)

- (CGSize)boundingSize:(CGSize)size font:(UIFont*)font
{
    CGSize resultSize;
    
#ifdef __IPHONE_7_0
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:context:)]) {
        resultSize = [self boundingRectWithSize:size
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:font}
                                        context:nil].size;
    }
    else {
#   pragma clang diagnostic push
#   pragma clang diagnostic ignored "-Wdeprecated-declarations"
        resultSize = [self sizeWithFont:font
                      constrainedToSize:size
                          lineBreakMode:NSLineBreakByWordWrapping];
#   pragma clang diagnostic pop
    }
#else
#   pragma clang diagnostic push
#   pragma clang diagnostic ignored "-Wdeprecated-declarations"
    resultSize = [self sizeWithFont:font
                  constrainedToSize:size
                      lineBreakMode:NSLineBreakByWordWrapping];
#   pragma clang diagnostic pop
#endif
    resultSize.width = ceil(resultSize.width);
    resultSize.height = ceil(resultSize.height);
    
    return resultSize;
}

@end


신고
Posted by 초프(초보 프로그래머)