属性文本简介
一个NSAttributedString对象管理字符串和属性相关的设置(例如,字体、字距)适用于单个字符或字符串中的字符的范围。
- (instancetype)initWithAttributedString:(NSAttributedString *)attributedString 通过另外一个属性字符串创建
- (instancetype)initWithString:(NSString *)aString
attributes:(NSDictionary<NSString *,id> *)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. |
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
attrName
inRange:
(
NSRange
)
enumerationRange
options:
(
NSAttributedStringEnumerationOptions
)
opts
usingBlock:
(
void (^)(id value, NSRange range, BOOL *stop)
)
block
- (void)enumerateAttributesInRange:(NSRange)enumerationRange
options:(NSAttributedStringEnumerationOptions)opts
usingBlock:(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.
mutableString获取其字符串
改变其内容:
- (void)deleteCharactersInRange:(NSRange)
aRange
改变属性:
- (void)setAttributes:(NSDictionary<NSString *,id> *)
attributes
range:(NSRange)aRange
- (void)addAttributes:(NSDictionary<NSString *,id> *)
attributes
range:(NSRange)aRange
改变属性字符串
- (void)appendAttributedString:(NSAttributedString*)attributedString
- (void)insertAttributedString:(NSAttributedString*)attributedString
atIndex:(NSUInteger)index
- (void)replaceCharactersInRange:(NSRange)aRange
withAttributedString:(NSAttributedString *)attributedString
- (void)setAttributedString:(NSAttributedString*)attributedString
这两个方法是只针对于可变属性文本字符串的,在编辑其属性的过程中,开始时调用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>
执行效果: