使用富文本在lable上展示不同颜色的文字,自定义label高度,自定义行间距
来源:互联网 发布:java 读取资源文件 编辑:程序博客网 时间:2024/05/23 11:34
废话不多说,直接上代码
第一段代码主要是创建富文本,并给文字赋值给label,调整文字的颜色字体行间距等
- (void)createLabel{ UILabel * textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 250, 200, 20)]; textLabel.backgroundColor = [UIColor yellowColor]; //调整行间距 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = 10;// 字体的行间距 //设置字体大小 textLabel.font = [UIFont systemFontOfSize:15.0]; textLabel.numberOfLines = 0; NSDictionary * attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:15.0],NSParagraphStyleAttributeName:paragraphStyle}; NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"如果一个属性总是使用同一个初始值,可以为其设置一个默认值。无论定义默认值还是在构造器中赋值,最终它们实现的效果是一样的,只不过默认值将属性的初始化和属性的声明结合的更紧密。使用默认值能让你的构造器更简洁、更清晰,且能通过默认值自动推导出属性的类型;同时,它也能让你充分利用默认构造器、构造器继承(后续章节将讲到)等特性。" attributes:attribute]; //设置字体不同的颜色 [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 50)]; [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(50, str.length - 50)]; [textLabel setAttributedText:str]; [self addSubview:textLabel]; //计算文字高度并调整lable高度 CGFloat height = [self setNameLabelWithText:str attribute:attribute]; textLabel.frame = CGRectMake(10, 250, 200, height); }
第二段通过文字属性计算label的高度,这个方法在开发过程中会经常用到。
- (CGFloat)setNameLabelWithText:(NSMutableAttributedString *)text attribute:(NSDictionary *)attribute{ NSString * str = [text string]; CGRect textRext = [str boundingRectWithSize:CGSizeMake(200, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil]; CGFloat height = textRext.size.height; return height; }
运行结果是酱紫的
0 0
- 使用富文本在lable上展示不同颜色的文字,自定义label高度,自定义行间距
- 计算label自定义行间距字间距,计算自定义行间距字间距的高度
- iOS中求出label中文字的行数和每一行的内容,带自定义行间距
- [转]iOS UILabel自定义行间距时获取高度
- 自定义行间距 多行输出 解决DrawText 无法自定义行间距的问题
- UILabel - 自定义行间距,字间距及段间距[并动态调节高度]
- Label 的富文本 与 自定义Label
- Lable的富文本
- Lable的富文本
- ZK 中在页面上同一个lable 不同颜色的代码
- easyui的自定义行工具栏
- iOS在一个Label中展示不同颜色的text
- label显示不同颜色的文字
- coreText自定义富文本Label
- coreText自定义富文本Label
- coreText自定义富文本Label
- coreText自定义富文本Label
- UILabel上展示不同颜色的文字(NSAttributedString)
- 6.15 喜刷刷 1 oj c 矩形的运算符重载
- Cookies 揭秘
- Android编程之LayoutInflater的inflate方法
- Source Insight学习笔记
- object-C与JAVA和C++对比
- 使用富文本在lable上展示不同颜色的文字,自定义label高度,自定义行间距
- LeetCode_30---Substring with Concatenation of All Words
- php标准规范
- (五)SDN 控制器 NOX 源码分析之—— Connection_manager
- 2015 Open Networking Summit 五大看点
- linux 系统命令
- 【转】各大公司使用的第三方库
- error loading /system/media/audio/ui/KeypressStandard.ogg
- {A} + {B}(set容器)