iOS_NSAttributeString
来源:互联网 发布:wampserver mac版 编辑:程序博客网 时间:2024/05/16 14:57
iOS_NSAttributeString
NSAttributeString属性及方法
NSAttributeString 类的作用是管理字符串和与字符串属性有关联的集合(例如,字体和字距),也称富文本。它适用于单个字符,或字符串某些范围的子字符。字符串与它们的属性相关联后称为属性字符串。本框架下有两个接口,NSAttributeString和 NSMutableAttributedString, 前者用于只读的属性字符串,后者用于可变的属性字符串。具体实现时,NSAttributedString维护了一个NSString,用来保存最原始的字符串,另有一个NSDictionary用来保存各个子串/字符的属性。
NSAttributedString 类的默认字体是 Helvetica体,大小为12-point,这可能与系统平台的默认字体有所不同。因此,你可能需要使用非默认的属性创建新的字符串以适合您的应用。您也可以使用NSParagraphStyle类及其子类NSMutableParagraphStyle封装所用的NSAttributedString类的段落或行距属性。
请注意,比较 NSAttributeString类时应使用 isEqual: 方法进行对比。对比的内容包括两个方面:一是,对逐个字符进行比较;二是,对对应字符的属性进行比较。如果一个字符串包含很多属性,例如attachments, lists, and tables,这样是不容易得到相匹配的结果的。
NSAttributedString核心API:
//字符串@property (readonly,copy) NSString *string;//长度@property (readonly)NSUInteger length;// 返回属性字符串给定索引处的字符属性// @ location 需要返回属性处的下标,这个值必须在所接收的字符串索引范围内// @ range :(如果不为NULL: 1.如果指定索引处存在属性,那么将返回有效索引范围内的属性名称。2. 如果指定索引处不存在属性,那么返回范围内的属性也不存在.)(range并不是必须的,可以传入NULL)- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range;- (id)attribute:(NSString *)attrName atIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range;/* * @ 提取子字符串 */- (NSAttributedString *)attributedSubstringFromRange:(NSRange)range;/* * @ 比较属性字符串 */- (BOOL)isEqualToAttributedString:(NSAttributedString *)other;/* * @ 初始化 NSAttributedString 类 * @ attrs,新属性字符串的属性 键-值 信息,见于 UIKit 框架下 NSAttirbuteString类 */// 返回一个用不含属性信息的给定字符串初始化的 NSAttributedString对象- (instancetype)initWithString:(NSString *)str;// 返回一个用指定属性信息及给定字符串初始化的 NSAttributedString对象- (instancetype)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;// 返回一个用给定字符串及其所带属性初始化的 NSAttributedString对象- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;/* * @ 列举字符串的属性 */- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(NSDictionary *attrs,NSRange range, BOOL *stop))block NS_AVAILABLE(10_6,4_0);- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(id value,NSRange range, BOOL *stop))block NS_AVAILABLE(10_6,4_0);
NSMutableAttributedString核心API:
@property (readonly,retain) NSMutableString *mutableString;//替换字符- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString;//设置字符串属性- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;- (void)setAttributedString:(NSAttributedString *)attrString;//添加字符串属性- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;//删除字符串属性- (void)removeAttribute:(NSString *)name range:(NSRange)range;//插入NSAttributedString- (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc;//拼接NSAttributedString- (void)appendAttributedString:(NSAttributedString *)attrString;//删除字符- (void)deleteCharactersInRange:(NSRange)range;- (void)beginEditing;- (void)endEditing;
NSAttributeString属性测试
代码实现:
self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 320, 500)]; self.titleLabel.numberOfLines = 0; self.titleLabel.layer.borderColor = [UIColor grayColor].CGColor; self.titleLabel.layer.borderWidth = 0.5; [self.view addSubview:self.titleLabel]; NSString *string = @"An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string"; /* 这句话就是对这个类的一个最简明扼要的概括。NSAttributedString管理一个字符串,以及与该字符串中的单个字符或某些范围的字符串相关的属性。它有一个子类NSMutableAttributedString * 具体实现时,NSAttributedString维护了一个NSString,用来保存最原始的字符串,另有一个NSDictionary用来保存各个子串/字符的属性。 */ /* 三种初始化方法,NSMutableAttributedString没有初始化方法,使用父类初始化方法, 使用initWithString:, initWithString:attributes:, 或者 initWithAttributedString: */ NSAttributedString *attStri = [[NSAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30]}]; NSMutableAttributedString *mAttStri = [[NSMutableAttributedString alloc] initWithString:string]; /* Character Attributes , 共21个属性名字 */ /* API: NSFontAttributeName */ //字体大小 及 字体类型 NSRange font_range = [string rangeOfString:@"An"]; [mAttStri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:font_range]; [mAttStri addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:17.0] range:NSMakeRange(10, 10)]; /* API: NSParagraphStyleAttributeName */ //值为NSParagraphStyle,设置段落属性,默认值为[NSParagraphStyle defaultParagraphStyle]返回的值。 /* NSMutableParagraphStyle与NSParagraphStyle包括一下属性 alignment //对齐方式 firstLineHeadIndent //首行缩进 headIndent //缩进 tailIndent //尾部缩进 lineBreakMode //断行方式 maximumLineHeight //最大行高 minimumLineHeight //最低行高 lineSpacing //行距 paragraphSpacing //段距 paragraphSpacingBefore //段首空间 baseWritingDirection //句子方向 lineHeightMultiple //可变行高,乘因数。 hyphenationFactor //连字符属性 */ NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];// style.alignment = NSTextAlignmentCenter; style.firstLineHeadIndent = 20; style.lineSpacing = 10; [mAttStri addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, mAttStri.length)]; /* NSForegroundColorAttributeName */ //值为UIColor,字体颜色,默认为黑色。 [mAttStri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, mAttStri.length)]; /* NSBackgroundColorAttributeName */ //值为UIColor,字体背景色,默认没有。 [mAttStri addAttribute:NSBackgroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, 20)]; /* NSKernAttributeName */ //值为浮点数NSNumber,字距属性,默认值为0。 [mAttStri addAttribute:NSKernAttributeName value:@3 range:NSMakeRange(0, mAttStri.length)]; /* NSStrikethroughStyleAttributeName */ /*值为整型NSNumber,可取值为 enum { NSUnderlineStyleNone = 0×00, NSUnderlineStyleSingle = 0×01, };设置删除线。 */ [mAttStri addAttribute:NSStrikethroughStyleAttributeName value:@3 range:NSMakeRange(3, 7)]; /* NSStrikethroughColorAttributeName */ //这个属性的值是一个UIColor对象。默认值为nil,表示颜色同ForegroundColor相同。 [mAttStri addAttribute:NSStrikethroughColorAttributeName value:[UIColor blueColor] range:NSMakeRange(3, 3)]; /* NSUnderlineStyleAttributeName */ //同上,设置下划线。 [mAttStri addAttribute:NSUnderlineStyleAttributeName value:@2 range:NSMakeRange(6, 5)]; /* NSUnderlineColorAttributeName */ //这个属性的值是一个UIColor对象。默认值为nil,表示颜色同ForegroundColor相同。 [mAttStri addAttribute:NSUnderlineColorAttributeName value:[UIColor blackColor] range:NSMakeRange(6, 5)]; /* NSStrokeWidthAttributeName */ //值为浮点数NSNumber。设置比画的粗细。 [mAttStri addAttribute:NSStrokeWidthAttributeName value:@10 range:NSMakeRange(50, 30)]; /* NSStrokeColorAttributeName */ //值为UIColor,默认值为nil,设置的属性同ForegroundColor。 [mAttStri addAttribute:NSStrokeColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(50, 20)]; /* NSShadowAttributeName */ //值为NSShadow,设置比画的阴影,默认值为nil。 NSShadow *shadow = [[NSShadow alloc]init]; shadow.shadowOffset = CGSizeMake(10, 10); shadow.shadowColor = [UIColor greenColor]; [mAttStri addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(20, 10)]; /* NSBaselineOffsetAttributeName */ //此属性的值是包含一个浮点值的NSNumber对象,表示的字符从基线偏移的NSNumber对象,默认值是0。 [mAttStri addAttribute:NSBaselineOffsetAttributeName value:@5 range:NSMakeRange(112, 10)]; /* NSObliquenessAttributeName */ //此属性的值是包含一个浮点值的NSNumber对象,指示倾斜被应用到图形。默认值为0,表示没有倾斜。 [mAttStri addAttribute:NSObliquenessAttributeName value:@0.8 range:NSMakeRange(135, 15)]; /* NSLigatureAttributeName */ //值为整型NSNumber,连字属性,一般中文用不到,在英文中可能出现相邻字母连笔的情况。0为不连笔;1为默认连笔,也是默认值; [mAttStri addAttribute:NSLigatureAttributeName value:@0 range:NSMakeRange(0, mAttStri.length)]; /* NSVerticalGlyphFormAttributeName */ //值为整型NSNumber,0为水平排版的字,1为垂直排版的字。 //未看出效果 [mAttStri addAttribute:NSVerticalGlyphFormAttributeName value:@0 range:NSMakeRange(1, 10)]; /* NSTextEffectAttributeName */ //这个属性的值是一个NSString对象,目前只有图版印刷效果可用此。使用此属性设置文本特殊效果,属性的默认值为nil,表示没有文本效应。 //未看出效果 [mAttStri addAttribute:NSTextEffectAttributeName value:NSTextEffectLetterpressStyle range:NSMakeRange(80, 10)]; /* NSLinkAttributeName */ //此属性的值是NSURL对象(首选)或一个NSString对象。设置链接属性,点击后调用浏览器打开指定URL地址,此属性的默认值为nil,表示没有链接。 //下文测试#pragma mark ** 未测试 /* NSAttachmentAttributeName */ //这个属性的值是一个NSTextAttachment对象。设置文本附件,常用于文字图片混排,此属性的默认值为nil,表示无附件。 //未测试 /* NSExpansionAttributeName */ //未测试 //此属性的值是包含一个浮点值的NSNumber对象,表示的扩展因子被应用到日志的NSNumber对象符号。默认值为0,表示没有扩展。 /* NSWritingDirectionAttributeName */ //未测试 //初步理解为表示嵌套的写作方向 self.titleLabel.attributedText = mAttStri; [self.titleLabel sizeToFit];
NSAttributeString实现UITextView链接
使用 NSLinkAttributeName 属性为textView添加链接:
NSDictionary *attrsDic = @{NSForegroundColorAttributeName: [UIColor blackColor],NSBackgroundColorAttributeName: [UIColor clearColor],NSBaselineOffsetAttributeName: [NSNumber numberWithFloat:5.0],NSKernAttributeName: [NSNumber numberWithFloat:1.0],NSLigatureAttributeName: [NSNumber numberWithFloat:1],NSFontAttributeName:[UIFont systemFontOfSize:16]}; NSString *text =@"点击进入百度"; NSMutableAttributedString *attributedstr = [[NSMutableAttributedString alloc]initWithString:text attributes:attrsDic]; while (true) { NSRange range = [text rangeOfString:@"百度" options:NSCaseInsensitiveSearch range:NSMakeRange(0, text.length)]; if (range.length == 0) { break; } [attributedstr addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"http://www.baidu.com"] range:range]; [attributedstr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:range]; } UITextView *mTextView = [[UITextView alloc]initWithFrame:CGRectMake(10,50,self.view.frame.size.width-20,self.view.frame.size.height-100)]; mTextView.delegate = self; mTextView.editable =NO; mTextView.font = [UIFont systemFontOfSize:16]; mTextView.attributedText = attributedstr; [self.view addSubview:mTextView]; //设置链接的属性 NSDictionary *linkAttributes =@{NSForegroundColorAttributeName: [UIColor blueColor],NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle]}; mTextView.linkTextAttributes = linkAttributes;
点击事件:
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { NSLog(@"shouldInteractWithURL:%@", URL); return YES; // let the system open this URL}
使用NSAttributeString实现关键字高亮
#pragma mark - 关键字高亮//参数为字符串, 返回值类型为一个NSMutableAttributedString(有颜色的字)- (NSMutableAttributedString *)highLight:(NSString *)str key:(NSString *)key{ //创建一个可变NSMutableAttributedString,每次搜索到关键字,就按照所搜索到的关键字位置,将NSMutableAttributedString该处的字符颜色变红 NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str]; //将attributedStr所有字符的颜色变白,字符默认颜色为黑色,如果你不想改成白色,这行代码可以删除 [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, attributedStr.length)]; //创建一个位置,让它初值为0,以后每次搜索到关键字,让它等于关键字后第一个字符的位置,然后从这个位置开始继续搜索 NSInteger iLocation =0; while (true) { //获得关键字在searchStr中出现的位置 NSRange range = [str rangeOfString:key options:NSCaseInsensitiveSearch range:NSMakeRange(iLocation, str.length - iLocation)]; //如果没有搜索到关键字,则停止搜索 if (range.length == 0) { break; } //将attributedStr该位子处的字符串变红 [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range]; iLocation = range.location+range.length; } //返回将关键字变红后的字符串attributedStr return attributedStr; }