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

来源:互联网 发布:linux怎么查看用户权限 编辑:程序博客网 时间:2024/04/28 02:35

比如有这么几个数据:

@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;



0 0
原创粉丝点击