iOS AttributeString(富文本)
2015-11-08 10:50
351 查看
说几句
在 iOS 的开发过程中,label, UITextField 等显示文本的控件使用 AttributeString 是非常常见的,当然如果你的 app 对文字的排版要求比较高,这时候就仅仅使用文本控件的 attributeString 属性就无法满足你的需求,这时最好去使用一些排版引擎(请自行搜索,好吧,相关的引擎我也不熟悉啦)。有码有真相
/* * * 使字符串分成两段不同的字体(大小和颜色) * @param originString 需要显示不同字体的字符串 * @param firstPartColor 第一段文本的字体颜色 * @param firstPartFont 第一段文本使用的字体(大小,何种字体) * @param length 第一段文本的长度 * @param secondPartColor 第二段文本的字体颜色 * @param secondPartFont 第二段文本使用的字体(大小,何种字体) * @param lineSpace 行间距 * * @return 采用了相关字体的富文本 */ + (NSMutableAttributedString *)generateAttributeStringWithString:(NSString *)originString withFirstPartColor:(UIColor *)firstPartColor withFirstPartFont:(UIFont *)firstPartFont withFristPartLength:(NSInteger)length nwithSecondPartColor:(UIColor *)secondPartColor withSecondPartFont:(UIFont *)secondPartFont withLineSpace:(float)lineSpace { NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:originString]; [attriStr addAttribute:NSForegroundColorAttributeName value:firstPartColor range:NSMakeRange(0, length)]; [attriStr addAttribute:NSFontAttributeName value:firstPartFont range:NSMakeRange(0, length)]; long redisualLength = originString.length - length; [attriStr addAttribute:NSForegroundColorAttributeName value:secondPartColor range:NSMakeRange(length, redisualLength)]; [attriStr addAttribute:NSFontAttributeName value:secondPartFont range:NSMakeRange(length, redisualLength)]; //调整行间距 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineSpacing:lineSpace]; [attriStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, originString.length)]; return attriStr; }
来个 demo 截图
相关文章推荐
- 第一个OC的类
- iOS中常用的几种传值方式
- 25个增强iOS应用程序性能的提示和技巧(高级篇)
- iOS开发知识与能力体系 思维导图
- iOS7 SDK新特性
- iOS项目的目录结构和开发流程
- IOS Table中Cell的重用reuse机制分析
- IOS开发之深拷贝与浅拷贝(mutableCopy与Copy)详解
- IOS多线程之Block编程
- iOS 开发者能用上的 10 个 Xcode 插件
- 实际案例讲解iOS设计模式——MVC模式
- IOS用CGContextRef画各种图形(文字、圆、直线、弧线、矩形、扇形、椭圆、三角形、圆角矩形、贝塞尔曲线、图片)
- iOS中正确的截屏姿势
- iOS开发Xcode7真机调试教程
- iOS中的图像处理(三)——混合运算
- iOS中的图像处理(二)——卷积运算
- iOS中的图像处理(一)——基础滤镜
- IOS中使用像素位图(CGImageRef)对图片进行处理
- IOS 编程中引用第三方的方类库的方法及常见问题
- iOS 判断字符串是否为空