UITextView使用 sizeWithFont:constrainedToSize:lineBreakMode:计算自适应文本高度
2012-10-10 11:32
561 查看
前不久QA报了个文字显示不全的bug,我看了下代码,发现是计算高度出了问题。之前的同事在UITableViewCell中使用了UITextView,但是计算高度时使用了和UILabel相同的的方法。
其实UITextView在上下左右分别有一个8px的padding,当使用[NSString sizeWithFont:constrainedToSize:lineBreakMode:]时,需要将UITextView.contentSize.width减去16像素(左右的padding 2 x 8px)。同时返回的高度中再加上16像素(上下的padding),这样得到的才是UITextView真正适应内容的高度。
示例代码如下:
+ (float) heightForTextView: (UITextView *)textView WithText: (NSString *) strText{
float fPadding = 16.0; // 8.0px x 2
CGSize constraint = CGSizeMake(textView.contentSize.width - fPadding, CGFLOAT_MAX);
CGSize size = [strText sizeWithFont: textView.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
float fHeight = size.height + 16.0;
return fHeight;
}本文出自 “范国锋” 博客,请务必保留此出处http://wicrewoft.blog.51cto.com/210706/1020243
其实UITextView在上下左右分别有一个8px的padding,当使用[NSString sizeWithFont:constrainedToSize:lineBreakMode:]时,需要将UITextView.contentSize.width减去16像素(左右的padding 2 x 8px)。同时返回的高度中再加上16像素(上下的padding),这样得到的才是UITextView真正适应内容的高度。
示例代码如下:
+ (float) heightForTextView: (UITextView *)textView WithText: (NSString *) strText{
float fPadding = 16.0; // 8.0px x 2
CGSize constraint = CGSizeMake(textView.contentSize.width - fPadding, CGFLOAT_MAX);
CGSize size = [strText sizeWithFont: textView.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
float fHeight = size.height + 16.0;
return fHeight;
}本文出自 “范国锋” 博客,请务必保留此出处http://wicrewoft.blog.51cto.com/210706/1020243
相关文章推荐
- UITextView使用 sizeWithFont:constrainedToSize:lineBreakMode:计算自适应文本高度
- UITextView使用 sizeWithFont:constrainedToSize:lineBreakMode:计算自适应文本高度
- 宽度高度sizeWithFont:constrainedToSize:lineBreakMode的使用
- sizeWithFont:constrainedToSize:lineBreakMode的使用
- UITextView使用sizeWithFont:计算自适应文本高度
- sizeWithFont:constrainedToSize:lineBreakMode的使用
- sizeWithFont:constrainedToSize:lineBreakMode的使用 (2012-03-20 10:48:40)转载▼ 标签: 宽度 字符串 获取 指定 用于 杂谈 分类:
- IOS7.0 sizeWithFont:constrainedToSize:lineBreakMode:方法 iOS7 Deprecated
- boundingRectWithSize:options:attributes:context:代替sizeWithFont:constrainedToSize:lineBreakMode:
- IOS7.0 sizeWithFont:constrainedToSize:lineBreakMode:方法 iOS7 Deprecated
- IOS7.0 sizeWithFont:constrainedToSize:lineBreakMode:方法
- IOS7.0 sizeWithFont:constrainedToSize:lineBreakMode:方法
- [ios]tableView内部cell因内容大小变换 而变化 sizeWithFont:constrainedToSize: lineBreakMode:
- sizeWithFont:constrainedToSize:lineBreakMode:方法在IOS7中过时
- 自动调整文字高度With what should I replace the deprecated sizeWithFont:contrainedToSize:lineBreakMode method?
- IOS高访微信聊天对话界面(sizeWithFont:constrainedToSize和stretchableImageWithLeftCapWidth的使用)
- IOS高访微信聊天对话界面(sizeWithFont:constrainedToSize和stretchableImageWithLeftCapWidth的使用)
- 计算文本高度 UILabel和sizeWithFont方法
- IOS高访微信聊天对话界面(sizeWithFont:constrainedToSize和stretchableImageWithLeftCapWidth的使用)
- IOS高访微信聊天对话界面(sizeWithFont:constrainedToSize和stretchableImageWithLeftCapWidth的使用)