IOS 根据文字字符串计算size

方法一;

  • (CGSize) getAttributeSizeWithText:(NSString *)text fontSize:(int)fontSize
    {
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]}];
    if (isIos7Later) {
    size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]}];
    }else{
    NSAttributedString *attributeSting = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]}];
    size = [attributeSting size];
    }
    return size;
    }

方法二,直接sizetofit方法,会自动换行,然后其frame就是对应的实际大小
方法三

import "Util.h"

import

@implementation Util

  • (CGSize)sizeWithString:(NSString *)string font:(UIFont *)font constraintSize:(CGSize)constraintSize
    {
    CGSize stringSize = CGSizeZero;

    NSDictionary *attributes = @{NSFontAttributeName:font};
    NSInteger options = NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
    CGRect stringRect = [string boundingRectWithSize:constraintSize options:options attributes:attributes context:NULL];
    stringSize = stringRect.size;

    return stringSize;
    }

来自:http://www.cocoachina.com/bbs/read.php?tid=456568

你可能感兴趣的:(IOS 根据文字字符串计算size)