iOS 富文本(NSAttributedstring,NSMut

2016-04-07  本文已影响0人  Song___

在iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给几个文字加删除线或者下划线的需求。之前在网上找一些资料,有的是重绘UILable的textlayer,有的是用H5实现,还有的甚至就是多放几个lable设置来实现的,都比较麻烦,效果很不理想。后来了解了NSMutableAttributedString(带属性的字符串),上面的一些需求都可以很简单的实现。

1.实例化方法和使用方法

实例化方法:使用字符串初始化

- (id)initWithString:(NSString *)str;

例:

NSMutableAttributedString * attstr = [[NSMutableAttributedString alloc] initWithString:@"今天天气好晴朗,处处好风光"];

- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;

//定义字典,设置文本的属性

NSMutableDictionary * attributeDict = [NSMutableDictionary dictionary];

attributeDict[NSForegroundColorAttributeName] = [UIColorredColor];

attributeDict[NSFontAttributeName] = [UIFont systemFontOfSize:17];

NSMutableAttributedString * attributedStr = [[NSMutableAttributedString alloc] initWithString:@"今天天气好晴朗,处处好风光" attributes: attributeDict];

UITextField* textFiled = [[UITextField alloc] initWithFrame:CGRectMake(100,100,120,30)];

//可以改变placeholder的颜色,字号等等。

textFiled.attributedPlaceholder= attributedStr;

- (id)initWithAttributedString:(NSAttributedString *)attester;

使用NSAttributedString初始化,跟NSMutableString,NSString类似

使用方法:

为某一范围内文字设置多个属性

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

为某一范围内文字添加某个属性

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

为某一范围内文字添加多个属性

- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

移除某范围内的某个属性

- (void)removeAttribute:(NSString *)name range:(NSRange)range;

2.常见的属性及说明

NSFontAttributeName 字体

NSParagraphStyleAttributeName 段落格式

NSForegroundColorAttributeName 字体颜色

NSBackgroundColorAttributeName 背景颜色

NSStrikethroughStyleAttributeName 删除线格式

NSUnderlineStyleAttributeName 下划线格式

NSStrokeColorAttributeName 删除线颜色

NSStrokeWidthAttributeName 删除线宽度

NSShadowAttributeName 阴影

更多方法和属性说明详见苹果官方说明文档:

NSMutableAttributedString Class Reference

另外,其他可以设置text的控件(如UIButtonUITextField)也都有该属性,该文章不够详细,只是简单介绍,其他效果的实现参考API中更多的属性及使用方法

上一篇下一篇

猜你喜欢

热点阅读