热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

iOS使用NSMutableAttributedString实现富文本(不同颜色字体、划线等等)

在iOS开发中,常常会有某一区间一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求,了解到NSMuttableAttstring(带属性的字符串),来实现这些需求.使用方法:为某一范

在iOS开发中,常常会有某一区间一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求,

了解到NSMuttableAttstring(带属性的字符串),来实现这些需求.


使用方法:

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

- (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 

example1:

   UILabel *label = [[UILabelalloc] initWithFrame:CGRectMake(0,0, 100,40)];

                    [self.viewaddSubview:label];

                    label.text =@"haha";

                    

                   NSAttributedString *attrStr =

                    [[NSAttributedStringalloc]initWithString:label.text

                                                  attributes:

                    @{NSFontAttributeName:[UIFontsystemFontOfSize:20.f],

                      NSForegroundColorAttributeName:[UIColorcyanColor],

                      NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle|NSUnderlinePatternSolid),

                      NSStrikethroughColorAttributeName:[UIColorblackColor]}];

                    label.attributedText = attrStr;

效果就是这样的
example2:

    NSString *str =@"哈哈哈(假日)";                    

                   NSMutableAttributedString *attributeStr = [[NSMutableAttributedStringalloc] initWithString:str];

                    [attributeStrsetAttributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:15],NSForegroundColorAttributeName:[UIColorcolorWithRed:0.206green:0.309blue:1.000alpha:1.000]}range:NSMakeRange(4,2)];

                    cell.textLabel.attributedText = attributeStr; 

哈哈哈(假日), 效果是这样的


更多详细请看:点击打开苹果官方链接
推荐阅读
author-avatar
手机用户2502918753
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有