boundingRectWithSize 的使用, 计算UILable高度, 包含Emoji及多属性string.
来源:互联网 发布:产品经理与程序员对骂 编辑:程序博客网 时间:2024/05/13 14:55
iOS的文字高度计算一直是个问题, 苹果也一直在改, 这几天看了一下 boundingRectWithSize 方法.
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);
踩了几个坑后, 总算找到比较好的使用方法.
参考: http://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size
使用时的注意事项:
1: NSAttributedString 的每个部分都要至少设置两个属性:
NSFontAttributeName
NSForegroundColorAttributeName
2: NSStringDrawingOptions 的值, 在多行的情况下, 至少要有
NSStringDrawingUsesLineFragmentOrigin
NSStringDrawingUsesFontLeading
3: 如果文字中可能会出现emoji表情的话, emoji的高度比文字要高一点点,
我的方便是简单的在高度基础上加了两个像素.
(用CoreText可能会好一些, 但相对复杂.)
附代码:
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:fullDescAndTagStr];NSRange allRange = [fullDescAndTagStr rangeOfString:fullDescAndTagStr];[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:allRange];[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:allRange];NSRange destRange = [fullDescAndTagStr rangeOfString:tagStr];[attrStr addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x009cdd) range:destRange];CGFloat titleHeight;NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX) options:options context:nil];titleHeight = ceilf(rect.size.height);return titleHeight+2; // 加两个像素,防止emoji被切掉.
0 0
- boundingRectWithSize 的使用, 计算UILable高度, 包含Emoji及多属性string
- boundingRectWithSize 的使用, 计算UILable高度, 包含Emoji及多属性string.
- UILable的使用,文本高度的计算boundingRectWithSize
- 使用boundingRectWithSize计算内容高度的坑
- 使用boundingRectWithSize计算内容高度的坑
- boundingRectWithSize 的使用,计算Label高度
- 使用boundingRectWithSize计算内容高度的
- iOS 使用 boundingRectWithSize: 计算 UILabel 高度错误的解决方案
- UIKit-boundingRectWithSize计算多行UILabel的文字高度
- 计算动态UILable的高度
- boundingRectWithSize 动态计算文字的高度
- boundingRectWithSize计算label 高度
- 计算UILable格式内容的高度
- IOS7中动态计算UILable的高度
- boundingRectWithSize计算高度不准确
- boundingRectWithSize计算高度不准确
- boundingRectWithSize 7.0以后计算文本高度的方法
- IOS BUG记录 boundingRectWithSize计算内容宽度高度的问题
- 【jQuery】 ajax 提交表单问题--双击会重复提交;success函数不执行
- 9.1 数据库事务概述
- (OK) CORE - 不能正常初始化 - Fedora23 - /var/log/core-daemon.log - /root/.core/configs/m-MPE-manet.imn
- CentOS系统安装VNC详细步骤
- 按下开机键,电脑都做了哪些事
- boundingRectWithSize 的使用, 计算UILable高度, 包含Emoji及多属性string.
- 【转载】iOS ASI http 框架详解
- AndroidStudio设置自定义代码格式化
- malloc、calloc、realloc注意点
- 浅析总结 Android Studio 中 Gradle 配置运行
- android studio 启动项目时“Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled”
- 用MATLAB作图像识别所需要注意的细节!
- Android-RecyclerView使用(三) 实现下拉刷新,上拉自动加载
- 复制 粘贴 转发功能的实现