美文网首页iOS 开发
IOS 根据文字字符串计算size

IOS 根据文字字符串计算size

作者: Johnny_Chang | 来源:发表于2016-01-14 11:21 被阅读9232次

方法一;

  • (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 <CommonCrypto/CommonDigest.h>

@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

相关文章

网友评论

  • LeeCen:还是不很懂方法二,能不能 详细说一下吗?或 demo?
    Johnny_Chang:@CoderPan 嗯,sizetofit就是自适应文字长度
    PZcoder:方法二是直接Label自己根据文字内容及文字大小,自己设置frame。

本文标题:IOS 根据文字字符串计算size

本文链接:https://www.haomeiwen.com/subject/okickttx.html