【iOS开发】NSAttributedString和NSMutableAttributedString

属性文本简介

一个NSAttributedString对象管理字符串和属性相关的设置(例如,字体、字距)适用于单个字符或字符串中的字符的范围。

字符及其属性的关联被称为属性字符串。类簇的两个公共接口NSAttributedString和NSMutableAttributedString分别声明了只读属性的和可变属性的字符串。
一个属性的字符串用name标识属性,使用NSDictionary对象在给定的name存储一个值.你可以分配任何范围内(这取决于你的应用程序解释自定义属性)的属性。如果你用的是Core Text框架内部的属性字符串 你也可以用这个框架定义的属性秘钥来标示你的属性。在iOS中 标准属性键 都被描述成了『常量』一类在UIkit参考中有描述。在OS X中,标准的属性键是在nsattributedstring应用套件添加参考“常数”一节中描述的。
你可以使用任何接受它们的接口,例如Core Text。UIKit和 application kit也提供了NSMutableString的子类 名为NSTextStorage 为文本处理系统扩展提供存储。iOS6之后 你可以在文本师徒中使用属性字符串来显示格式化文本,和一些其他控件。
AppKit和UIKit还定义了基本属性字符串的接口的扩展,允许你在当前图形上下文画内容。
对于nsattributedstring对象的默认字体Helvetica 12点,这可能与该平台的默认系统字体不同。因此,您可能希望为您的应用程序创建新的带有非默认属性的字符串。你也可以使用NSParagraphStyle类及其子类NSmutableparagraphstyle封装段落属性,或封装NSAttributedString类的通用的属性。
要知道NSAttributedString比较对象相等是用isEqual方法。这样的比较是不可能产生一个匹配的字符串,如果字符串有很多的属性,如附件,列表,和表格、

NSAttributedString和Core Fundation之间用CFAttributedStringRef来联系。

NSAttributedString

创建一个NSAttributedString对象:
- ( instancetype ) initWithString: ( NSString * ) aString //通过字符串创建
- (instancetype)initWithAttributedString:(NSAttributedString *)attributedString 通过另外一个属性字符串创建
- (instancetype)initWithString:(NSString *)aStringattributes:(NSDictionary<NSString *,id> *)attributes//通过字符串和属性创建
参数:attributes

The attributes for the new attributed string. For information about where to find the attribute keys you can include in this dictionary, see the overview section of this document.

属性信息:
@property ( readonly ,   copy )   NSString  * string
@property(readonly) NSUInteger length
获取属性信息
- ( NSDictionary<NSString *,id> * ) attributesAtIndex: ( NSUInteger ) index   effectiveRange: ( NSRangePointer ) aRange
- (NSDictionary<NSString *,id> *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit
属性字符串比较
- (BOOL)isEqualToAttributedString:(NSAttributedString *)otherString
提取子串
- (NSAttributedString *)attributedSubstringFromRange:(NSRange)aRange
枚举属性字符串中的属性
- ( void ) enumerateAttribute: ( NSString * ) attrName  inRange: ( NSRange ) enumerationRange   options: ( NSAttributedStringEnumerationOptions ) opts  usingBlock: ( void (^)(id value, NSRange range, BOOL *stop) ) block
- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)optsusingBlock:(void (^)(NSDictionary<NSString *,id> *attrs, NSRange range, BOOL *stop))block
常量:
NSAttributedStringEnumerationOptions;
NSAttributedStringEnumerationReverse
NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
具体支持属性有:

/************************ Attributes ************************/

// Predefined character attributes for text. If the key is not in the dictionary, then use the default values as described below.

UIKIT_EXTERN NSString * const NSFontAttributeName NS_AVAILABLE(10_0, 6_0);                // UIFont, default Helvetica(Neue) 12前景色

UIKIT_EXTERN NSString * const NSParagraphStyleAttributeName NS_AVAILABLE(10_0, 6_0);      // NSParagraphStyle, default defaultParagraphStyle

UIKIT_EXTERN NSString * const NSForegroundColorAttributeName NS_AVAILABLE(10_0, 6_0);     // UIColor, default blackColor

UIKIT_EXTERN NSString * const NSBackgroundColorAttributeName NS_AVAILABLE(10_0, 6_0);     // UIColor, default nil: no background

UIKIT_EXTERN NSString * const NSLigatureAttributeName NS_AVAILABLE(10_0, 6_0);            // NSNumber containing integer, default 1: default ligatures, 0: no ligatures

UIKIT_EXTERN NSString * const NSKernAttributeName NS_AVAILABLE(10_0, 6_0);                // NSNumber containing floating point value, in points; amount to modify default kerning. 0 means kerning is disabled.

UIKIT_EXTERN NSString * const NSStrikethroughStyleAttributeName NS_AVAILABLE(10_0, 6_0);  // NSNumber containing integer, default 0: no strikethrough

UIKIT_EXTERN NSString * const NSUnderlineStyleAttributeName NS_AVAILABLE(10_0, 6_0);      // NSNumber containing integer, default 0: no underline

UIKIT_EXTERN NSString * const NSStrokeColorAttributeName NS_AVAILABLE(10_0, 6_0);         // UIColor, default nil: same as foreground color

UIKIT_EXTERN NSString * const NSStrokeWidthAttributeName NS_AVAILABLE(10_0, 6_0);         // NSNumber containing floating point value, in percent of font point size, default 0: no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0)

UIKIT_EXTERN NSString * const NSShadowAttributeName NS_AVAILABLE(10_0, 6_0);              // NSShadow, default nil: no shadow

UIKIT_EXTERN NSString *const NSTextEffectAttributeName NS_AVAILABLE(10_10, 7_0);          // NSString, default nil: no text effect


UIKIT_EXTERN NSString * const NSAttachmentAttributeName NS_AVAILABLE(10_0, 7_0);          // NSTextAttachment, default nil

UIKIT_EXTERN NSString * const NSLinkAttributeName NS_AVAILABLE(10_0, 7_0);                // NSURL (preferred) or NSString

UIKIT_EXTERN NSString * const NSBaselineOffsetAttributeName NS_AVAILABLE(10_0, 7_0);      // NSNumber containing floating point value, in points; offset from baseline, default 0

UIKIT_EXTERN NSString * const NSUnderlineColorAttributeName NS_AVAILABLE(10_0, 7_0);      // UIColor, default nil: same as foreground color

UIKIT_EXTERN NSString * const NSStrikethroughColorAttributeName NS_AVAILABLE(10_0, 7_0);  // UIColor, default nil: same as foreground color

UIKIT_EXTERN NSString * const NSObliquenessAttributeName NS_AVAILABLE(10_0, 7_0);         // NSNumber containing floating point value; skew to be applied to glyphs, default 0: no skew

UIKIT_EXTERN NSString * const NSExpansionAttributeName NS_AVAILABLE(10_0, 7_0);           // NSNumber containing floating point value; log of expansion factor to be applied to glyphs, default 0: no expansion


UIKIT_EXTERN NSString * const NSWritingDirectionAttributeName NS_AVAILABLE(10_6, 7_0);    // NSArray of NSNumbers representing the nested levels of writing direction overrides as defined by Unicode LRE, RLE, LRO, and RLO characters.  The control characters can be obtained by masking NSWritingDirection and NSTextWritingDirection values.  LRE: NSWritingDirectionLeftToRight|NSWritingDirectionEmbedding, RLE: NSWritingDirectionRightToLeft|NSWritingDirectionEmbedding, LRO: NSWritingDirectionLeftToRight|NSWritingDirectionOverride, RLO: NSWritingDirectionRightToLeft|NSWritingDirectionOverride,


UIKIT_EXTERN NSString * const NSVerticalGlyphFormAttributeName NS_AVAILABLE(10_7, 6_0);   // An NSNumber containing an integer value.  0 means horizontal text.  1 indicates vertical text.  If not specified, it could follow higher-level vertical orientation settings.  Currently on iOS, it's always horizontal.  The behavior for any other value is undefined.


NSMutableAttributedString
NSMutableAttributedString是 NSAttributedString的子类。这由类簇管理的两个公共接口的主要差别在于, NSMutableAttributedString的属性字符串是可以改变属性的、
其API主要有
mutableString获取其字符串

改变其内容:

- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString

- (void)deleteCharactersInRange:(NSRange)aRange

改变属性:

- (void)setAttributes:(NSDictionary<NSString *,id> *)attributes range:(NSRange)aRange

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

- (void)addAttributes:(NSDictionary<NSString *,id> *)attributes range:(NSRange)aRange

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

改变属性字符串
- (void)appendAttributedString:(NSAttributedString*)attributedString
- (void)insertAttributedString:(NSAttributedString*)attributedString atIndex:(NSUInteger)index
- (void)replaceCharactersInRange:(NSRange)aRangewithAttributedString:(NSAttributedString *)attributedString
- (void)setAttributedString:(NSAttributedString*)attributedString

还有两个方法:
- ( void ) beginEditing
- (void)endEditing
这两个方法是只针对于可变属性文本字符串的,在编辑其属性的过程中,开始时调用beginEditing结束时调用 endEditing.在属性发生变化时 会发送消息给监听者。

实践
<span style="color:#ff0000;">DEMO</span>
<span style="font-size:14px;">属性设置相关
-(void)testNSAttributeString
{
    //1.创建一个标签
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 300, 260)];
    label.text = @"Label Text Content, This is a text label things attribute";
    label.numberOfLines = 0;
    [self.view addSubview:label];
    
    //2.富文本字符串 NSMutableAttributedString
    NSString * str = label.text;
    NSUInteger len =[str length];
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc]initWithString:str
                                           ];
    
    //设置字体
    UIFont * font = [UIFont systemFontOfSize:30];
    [attrStr addAttribute:NSFontAttributeName value:font range:[str rangeOfString:@"label"]];
    
    //设置粗体
    UIFont * blodFont = [UIFont boldSystemFontOfSize:33];
    [attrStr addAttribute:NSFontAttributeName value:blodFont range:[str rangeOfString:@"label"]];
    
    //设置颜色
    UIColor * color = [UIColor redColor];
    [attrStr addAttribute:NSForegroundColorAttributeName value:color range:[str rangeOfString:@"lab"]];
    
    //背景色
    UIColor * backColor = [UIColor blueColor];
    [attrStr addAttribute:NSBackgroundColorAttributeName value:backColor range:[str rangeOfString:@"bel"]];
    
    //字符间距
    [attrStr addAttribute:NSKernAttributeName value:@3 range:NSMakeRange(0, len)];
    //空心文字
    [attrStr addAttribute:NSStrokeWidthAttributeName value:@3 range:[str rangeOfString:@"Text"]];
    //文字描边颜色
    [attrStr addAttribute:NSStrokeColorAttributeName value:[UIColor greenColor] range:[str rangeOfString:@"Text"]];
    
    
    //删除线
    [attrStr addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid|NSUnderlineStyleThick) range:[str rangeOfString:@"Label"]];
    
    //删除线颜色
    [attrStr addAttribute:NSStrikethroughColorAttributeName value:[UIColor blackColor] range:[str rangeOfString:@"Label"]];
    
    //下滑线
    [attrStr addAttribute:NSUnderlineStyleAttributeName  value:@(NSUnderlineStyleDouble) range:[str rangeOfString:@"Content"]];
    
    //下划线颜色
        [attrStr addAttribute:NSUnderlineColorAttributeName  value:[UIColor purpleColor] range:[str rangeOfString:@"Content"]];
    label.attributedText = attrStr;
}


段落相关
-(void)testParagraphStyle
{
    NSString * str = _myLabel.text;
    NSMutableAttributedString * attr = [[NSMutableAttributedString alloc]initWithString:str];
    NSUInteger length = [str length];
    NSMutableParagraphStyle * style = [[NSParagraphStyle defaultParagraphStyle]mutableCopy];
    style.lineSpacing = 10;//增加行高
    style.firstLineHeadIndent = 30;//首行头缩进
    style.headIndent = 20;//头部缩进,相当于左padding
    style.tailIndent = -20;//相当于右padding
    style.lineHeightMultiple = 1.5;//行间距是多少倍
    style.alignment = NSTextAlignmentLeft;//对齐方式
    
    style.paragraphSpacing = 10;//段落后面的间距
    style.paragraphSpacingBefore = 20;//段落之前的间距
    [attr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, length)];
    _myLabel.attributedText = attr;
    //段落样式
    /*
     lineSpacing;                         来增加行距
     paragraphSpacing;
     alignment;                           对齐
     firstLineHeadIndent;                 段落开始的缩排像素
     headIndent;                          可调整全部文字的缩排距离,可当作左边 padding 使用
     tailIndent;                          可调整文字尾端的缩排距离。需要注意的是,这里指定的值可以当作文字显示的宽、而也可当作右边 padding 使用,依据输入的正负值而定:
     lineBreakMode;
     minimumLineHeight;
     maximumLineHeight;        而针对不同的字型与字号,我们可以透过指定最大与最小行距(maximumLineHeight 与 minimumLineHeight)来避免过高或过窄的状况发生。
     baseWritingDirection;
     lineHeightMultiple;                  想要调整行距,可以透过搭配使用 lineHeightMultiple 更改行距倍数
     paragraphSpacingBefore; 而若是文章内容有分段落的话,也可以透过指定段落结尾距离(paragraphSpacing)以及段落开头距离(paragraphSpacingBefore):
     hyphenationFactor;
     @property(readwrite,copy,NS_NONATOMIC_IOSONLY) NSArray *tabStops NS_AVAILABLE_IOS(7_0);
     @property(readwrite,NS_NONATOMIC_IOSONLY) CGFloat defaultTabInterval NS_AVAILABLE_IOS(7_0);
     */
}</span>

执行效果:


属性文本就到这里。有关核心文本相关,请移步:http://blog.csdn.net/a316212802/article/details/50530081




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值