本文简要介绍了NSAttributedString对象,包括其用途、实例化方法、属性操作及常见属性如字体、颜色、背景色等。此外,还涉及NSMutableParagraphStyle对象,用于设置文本的段落样式,如行间距、段落间距、缩进等。文中提供了多个富文本实例,如如何设置字体颜色、下划线、段落样式、在富文本中添加图片等,详细展示了NSAttributedString在实际应用中的灵活运用。最后,提到了如何通过UIView生成图片,并将其插入到NSAttributedString中,以满足更复杂的设计需求。
一.NSAttributedString简介
NSAttributedString对象管理适用于字符串中单个字符或字符范围的字符串和关联的属性集(例如字体和字距)。
1. 实例化方法:
//初始化字符串- (instancetype)initWithString:(NSString *)str; - (instancetype)initWithString:(NSString *)str attributes:(NSDictionary<NSString *,id> *)attrs; - (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;
2.使用方法:
//添加属性 - (void)addAttribute:(NSAttributedStringKey)name value:(id)value range:(NSRange)range; - (void)addAttributes:(NSDictionary<NSAttributedStringKey, id> *)attrs range:(NSRange)range;
//移除属性 - (void)removeAttribute:(NSString *)name range:(NSRange)range;
//代替,插入,拼接属性 - (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString; - (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc; - (void)appendAttributedString:(NSAttributedString *)attrString;
3.属性及说明
// NSFontAttributeName 设置字体属性 // NSForegroundColorAttributeNam 设置字体颜色 // NSBackgroundColorAttributeName 设置字体所在区域背景颜色 // NSLigatureAttributeName 设置连体属性 // NSKernAttributeName 设定字符间距 // NSStrikethroughStyleAttributeName 设置删除线 // NSStrikethroughColorAttributeName 设置删除线颜色 // NSUnderlineStyleAttributeName 设置下划线 // NSUnderlineColorAttributeName 设置下划线颜色 // NSStrokeWidthAttributeName 设置笔画宽度 // NSStrokeColorAttributeName 填充部分颜色 // NSShadowAttributeName 设置阴影属性 // NSTextEffectAttributeName 设置文本特殊效果 // NSBaselineOffsetAttributeName 设置基线偏移值 // NSObliquenessAttributeName 设置字形倾斜度 // NSExpansionAttributeName 设置文本横向拉伸属性 // NSWritingDirectionAttributeName 设置文字书写方向 // NSVerticalGlyphFormAttributeName 设置文字排版方向 // NSLinkAttributeName 设置链接属性 // NSAttachmentAttributeName 设置文本附件,取值为NSTextAttachment对象,常用于文字图片混排 // NSParagraphStyleAttributeName 设置文本段落排版格式,取值为 NSParagraphStyle 对象
二.NSMutableParagraphStyle简介
1.使用方法
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init]; style.lineSpacing = 10;//字体的行间距 style.firstLineHeadIndent = 30.0f;//首行缩进 NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@“测试数据”]; NSRange allRange = [hLab.text rangeOfString:@“测试数据”]; [attrStr addAttributes:@{NSParagraphStyleAttributeName:style} range:allRange];
2.属性及说明
lineSpacing; // 字体的行间距 paragraphSpacing; // 段与段之间的间距 alignment; // (两端对齐的)文本对齐方式(左,中,右,两端对齐,自然) firstLineHeadIndent; // 首行缩进 headIndent; // 整体缩进(首行除外) tailIndent; // 尾部缩进 NSLineBreakMode lineBreakMode;// 结尾部分的内容以……方式省略 minimumLineHeight; // 最低行高 maximumLineHeight; // 最大行高 NSWritingDirection baseWritingDirection; // 书写方向 lineHeightMultiple; // 行间距多少倍 paragraphSpacingBefore; // 段首行空白空 float hyphenationFactor; // 连字属性
三.富文本的常用实例
1.富文本颜色,字体,下划线
实现代码:
//设置颜色字体 NSMutableAttributedString *attribt = [[NSMutableAttributedString alloc] initWithString:@"¥99"]; [attribt addAttribute:NSFontAttributeName value: [UIFont systemFontOfSize:12*kScreenWidth/375] range:NSMakeRange(0, 1)];//设置字体的不同 NSRange strRange = {0,[attribtDic length]}; [attribt addAttribute:NSForegroundColorAttributeName value:RGB(255, 98, 36) range:strRange]; //设置颜色 _activictyPrice.attributedText = attribt; //设置中划线 NSMutableAttributedString *attribtDic = [[NSMutableAttributedString alloc] initWithString:@"¥240"]; [attribtDic addAttribute:NSForegroundColorAttributeName value:auxiliaryFontColor range:strRange]; //设置颜色 [attribtDic addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange]; _originPrice.attributedText = attribtDic;
2.设置段落,手行缩进,行间距
实现效果图
//设置段间距 NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.headIndent = 18;//缩进 [paragraphStyle setParagraphSpacing:5];//段间距 [paragraphStyle setLineSpacing:8];//行间距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])]; _textLabel.attributedText = attributedString; [_textLabel sizeToFit];
//求出显示这段文字的高度
CGRect rect = [attrStr boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
是苹果推荐的计算方法,遇到段落格式问题,例如行间距、缩进等格式设置需求,attributes传进来的字典中,包含我们设置的字体及格式,其中NSParagraphStyleAttributeName是设置段落风格,NSFontAttributeName是设置字体。
3.富文本中添加图片
设计要求
思路分析:
刚看到这个设计时,想到用UIView和UILabel控制,但是考虑换行时位置需要判断太多,换种思路,把"过去的店"这个用UIView转图片,然后后面用UILabel的富文本NSTextAttachment 添加一张图片道富文本上。
代码实现:
CGSize size = [IHUtility GetSizeByText:@“去过的店” sizeOfFont:self.tagFont width:300]; UILabel *tagLabel = [MyUtility createLabelWithFrame:CGRectMake(0, 0, size.width+5, self.frame.size.height) title:self.tagTitle textColor:self.tagColor font:[UIFont systemFontOfSize:self.tagFont] textAlignment:NSTextAlignmentCenter numberOfLines:0]; tagLabel.layer.borderColor =RGB(255, 98, 36).CGColor; tagLabel.layer.borderWidth = 1; tagLabel.layer.masksToBounds = YES; tagLabel.layer.cornerRadius = self.frame.size.height/2; NSMutableAttributedString *attributeSring=[[NSMutableAttributedString alloc]initWithString:self.showTitle]; NSTextAttachment *attch = [[NSTextAttachment alloc] init]; attch.image = [IHUtility imageWithUIView:tagLabel];//UIView转image NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch]; [attributeSring insertAttributedString:string atIndex:0]; self.attributedText = attributeSring;
//label转化成image +(UIImage*) imageWithUIView:(UIView*) view { CGSize size = view.bounds.size; UIGraphicsBeginImageContextWithOptions(size,NO, [UIScreen mainScreen].scale); CGContextRef ctx = UIGraphicsGetCurrentContext(); [view.layer renderInContext:ctx]; UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return tImage; }
4. 富文本点击事件
思路分析: 虽然用UILabel和UIButton组合也可以实现,比较麻烦,特别是像这种协议比较多的情况下,换种思路,用富文本字体颜色,点击方法来实现。
代码实现:
- (void)protocolIsSelect:(BOOL)select { NSString *policyPrompt = @"请遵守以下协议《易脚用户协议》和《易脚隐私协议》"; NSDictionary *attributes = @{NSForegroundColorAttributeName:[UIColor blackColor]}; NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:policyPrompt attributes:attributes]; [attStr addAttribute:NSLinkAttributeName value:@"yonghu://" range:[[attStr string] rangeOfString:@"《易脚用户协议》"]]; [attStr addAttribute:NSLinkAttributeName value:@"yinsi://" range:[[attStr string] rangeOfString:@"《易脚隐私协议》"]]; UIImage *image = [UIImage imageNamed: select == YES ? @"sel03" : @"sel"]; CGSize size = CGSizeMake(font + 2, font + 2); UIGraphicsBeginImageContextWithOptions(size, false, 0); [image drawInRect:CGRectMake(0, 2, size.width, size.height)]; UIImage *resizeImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; textAttachment.image = resizeImage; NSMutableAttributedString *imageString = [NSMutableAttributedString attributedStringWithAttachment:textAttachment]; [imageString addAttribute:NSLinkAttributeName value:@"checkbox://" range:NSMakeRange(0, imageString.length)]; [attStr insertAttributedString:imageString atIndex:0]; [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font] range:NSMakeRange(0, attStr.length)]; UITextView *textview = [[UITextView alloc] initWithFrame:CGRectMake(20,100,kScreenWidth-40,60)]; textview.attributedText = attStr; textview.linkTextAttributes = @{NSForegroundColorAttributeName: VgreenColor, NSUnderlineColorAttributeName: [UIColor lightGrayColor], NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)}; textview.delegate = self; textview.editable = NO; //必须禁止输入,否则点击将弹出输入键盘 textview.scrollEnabled = NO; [self.view addSubview:textview]; } - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { if ([[URL scheme] isEqualToString:@"yonghu"]) { NSLog(@"用户协议---------------"); return NO; } else if ([[URL scheme] isEqualToString:@"yinsi"]) { NSLog(@"隐私协议---------------"); return NO; } else if ([[URL scheme] isEqualToString:@"checkbox"]) { self.isSelect = !self.isSelect; [self protocolIsSelect:self.isSelect]; return NO; } return YES; }
以上四种需求是最常见的富文本使用方法,在此作为记录!
本篇独发金蝶云社区
推荐阅读