您的位置:首页 > 其它

对于单行/多行 字符串文本size的 获取,如何取得文本高度和宽度

2015-09-10 16:02 429 查看
比如有这么几个数据:

@property (nonatomic,assign) long Id;
@property (nonatomic,copy) NSString *createdAt;
@property (nonatomic,copy) NSString *mbtype;
@property (nonatomic,copy) NSString *profileImageUrl;
@property (nonatomic,copy) NSString *source;
@property (nonatomic,copy) NSString *text;
@property (nonatomic,copy) NSString *userName;

要获取文本字符串的size 可以这么做:
单行文本 createdAt , source userName 调用 (CGSize)sizeWithAttributes:(NSDictionary *)attrs; 来获取文本的高度和宽度

例:

CGFloat userNameX = CGRectGetMaxX(_avatar.frame) + kStatusTableViewCellControlSpacing;
CGFloat userNameY = avatarY;
CGSize userNameSize = [contacts.userName <span style="color:#FF0000;">sizeWithAttributes</span>:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
_userName.text = contacts.userName;
_userName.frame = CGRectMake(userNameX, userNameY, userNameSize.width, userNameSize.height);

多行文本text 调用(CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context ;方法来得到文本宽度和高度;同时注意在此之前需要设置文本控件的numberOfLines属性为0

例:

CGFloat textX=avatarX;
CGFloat textY=CGRectGetMaxY(_avatar.frame)+kStatusTableViewCellControlSpacing;
CGFloat textWidth=self.frame.size.width-kStatusTableViewCellControlSpacing*2;
CGSize textSize=[status.text <span style="color:#FF0000;">boundingRectWithSize</span>:CGSizeMake(textWidth, MAXFLOAT)
<span style="color:#FF0000;">options</span>:NSStringDrawingUsesLineFragmentOrigin
<span style="color:#FF0000;">attributes</span>:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellTextFontSize]} <span style="color:#FF0000;">context</span>:nil].size;
CGRect textRect=CGRectMake(textX, textY, textSize.width, textSize.height);
_text.text = contacts.text;
_text.frame = textRect;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: