一位谋、關(guān)于AttributedString
在iOS開(kāi)發(fā)過(guò)程中系統(tǒng)簡(jiǎn)單的封裝工具已經(jīng)不夠我們使用,為了更好的開(kāi)發(fā),蘋(píng)果公司為開(kāi)發(fā)者提供了一套豐富的API供開(kāi)發(fā)者們使用抹凳。其中開(kāi)發(fā)過(guò)程中使用最多的就是AttributedString了吧诬滩,AttributedString與NSString類(lèi)似霹粥,在iOS中AttributedString也分為NSAttributedString和NSMutableAttributedString,不同的是,AttributedString對(duì)象多了一個(gè)Attribute的概念驾锰,一個(gè)AttributedString的對(duì)象包含很多的屬性狂窑,每一個(gè)屬性都有其對(duì)應(yīng)的字符區(qū)域,使用NSRange來(lái)進(jìn)行描述浩淘。下面簡(jiǎn)單講解一下AttributedString的屬性及用法捌朴。
官方學(xué)習(xí)鏈接Attributed String Programming Guide
- 1.方式一:
首先初始化一個(gè)NSMutableAttributedString,然后向里面添加文字樣式张抄,最后將它賦給控件的AttributedText砂蔽,該方法適合于文本較少而又需要分段精細(xì)控制的情況。
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是第一種方式署惯,哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"];
[attrStr addAttribute: NSFontAttributeName value: [UIFont fontWithName: @"Papyrus" size: 15] range: NSMakeRange(0, attrStr.length)];
NSMutableParagraphStyle * style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 5.0;
[attrStr addAttribute: NSParagraphStyleAttributeName value: style range: NSMakeRange(0, attrStr.length)];
self.firstLabel.attributedText = attrStr;
- 2.方式二:
首先創(chuàng)建屬性字典左驾,初始化各種屬性,然后和需要控制的文本一起創(chuàng)建并賦值給控件的AttributedText极谊,該方法適合于需要控制的文本較多整體控制的情況诡右,通常是從文件中讀取的大段文本控制。
//第二種方式
NSDictionary * dict = @{NSFontAttributeName:[UIFont fontWithName: @"Papyrus" size: 15], [UIFont fontWithName: @"Papyrus" size: 15]:style };
NSMutableAttributedString * attrStr2 = [[NSMutableAttributedString alloc] initWithString:@"我是第二種方式轻猖,哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈" attributes:dict];
self.secondLabel.attributedText = attrStr2;
二 帆吻、 AttributedString究竟可以設(shè)置哪些屬性
- NSFontAttributeName
設(shè)置字體屬性,默認(rèn)值:字體:Helvetica(Neue) 字號(hào):12
獲取系統(tǒng)的字體:[UIFont familyNames]
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSFontAttributeName 字體:Papyrus 字號(hào):15"];
[attrStr addAttribute: NSFontAttributeName value: [UIFont fontWithName: @"Papyrus" size: 15] range: NSMakeRange(0, attrStr.length)];
- NSParagraphStyleAttributeName(后面具體講解)
該屬性所對(duì)應(yīng)的值是一個(gè) NSParagraphStyle/NSMutableParagraphStyle 對(duì)象咙边。該屬性在一段文本上應(yīng)用多個(gè)屬性猜煮。
NSMutableParagraphStyle * style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 10.0;
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSParagraphStyleAttributeName \\\\\\\\\\\\\\\\n行間距 10"];
[attrStr addAttribute: NSParagraphStyleAttributeName value: style range: NSMakeRange(0, attrStr.length)];
- NSForegroundColorAttributeName
設(shè)置字體顏色,取值為 UIColor對(duì)象样眠,默認(rèn)值為黑色
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSForegroundColorAttributeName 顏色orangeColor"];
[attrStr addAttribute: NSForegroundColorAttributeName value: [UIColor orangeColor] range: NSMakeRange(0, attrStr.length)];
- NSBackgroundColorAttributeName
設(shè)置字體所在區(qū)域背景顏色友瘤,取值為 UIColor對(duì)象,默認(rèn)值為nil, 透明色
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSBackgroundColorAttributeName 背景顏色red"];
[attrStr addAttribute: NSBackgroundColorAttributeName value: [UIColor redColor] range: NSMakeRange(0, attrStr.length)];
- NSLigatureAttributeName
設(shè)置連體屬性檐束,取值為NSNumber 對(duì)象(整數(shù))辫秧,0 表示沒(méi)有連體字符,1 表示使用默認(rèn)的連體字符被丧。2 表示使用所有連體符號(hào)盟戏。默認(rèn)值為 1(注意,iOS 不支持值為 2)如下圖'f' 'l'的連接
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSLigatureAttributeName 'fl' 連體屬性 0"];
[attrStr addAttribute: NSFontAttributeName value: [UIFont fontWithName: @"PingFang SC" size: 15] range: NSMakeRange(0, attrStr.length)];
[attrStr addAttribute: NSLigatureAttributeName value: @(0) range: NSMakeRange(0, attrStr.length)];
- NSKernAttributeName
設(shè)定字符間距甥桂,取值為 NSNumber 對(duì)象(整數(shù))柿究,正值間距加寬,負(fù)值間距變窄黄选。
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSKernAttributeName 字符間距 2"];
[attrStr addAttribute: NSKernAttributeName value: @(2) range: NSMakeRange(0, attrStr.length)];
- NSStrikethroughStyleAttributeName
設(shè)置刪除線蝇摸,取值為 NSNumber 對(duì)象(整數(shù))
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSStrikethroughStyleAttributeName 刪除線 1"];
[attrStr addAttribute: NSStrikethroughStyleAttributeName value: @(1) range: NSMakeRange(0, attrStr.length)];
- NSUnderlineStyleAttributeName
設(shè)置下劃線,取值為 NSNumber 對(duì)象(整數(shù))办陷,枚舉常量 NSUnderlineStyle中的值貌夕。默認(rèn)值是NSUnderlineStyleNone。
2.8.png
- NSStrokeColorAttributeName
設(shè)置填充顏色民镜。取值為 UIColor 對(duì)象,需要和NSStrokeWidthAttributeName設(shè)置描邊寬度啡专,這樣就能使文字產(chǎn)生鏤空效果。
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSStrokeColorAttributeName 配合NSStrokeWidthAttributeName使用"];
[attrStr addAttribute: NSStrokeColorAttributeName value: [UIColor redColor] range: NSMakeRange(0, attrStr.length)];
[attrStr addAttribute: NSStrokeWidthAttributeName value: @(2) range: NSMakeRange(0, attrStr.length)];
- NSStrokeWidthAttributeName
設(shè)置筆畫(huà)寬度制圈,取值為 NSNumber 對(duì)象(整數(shù))们童,負(fù)值填充效果畔况,正值中空效果。與NSStrokeColorAttributeName配合使用
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSStrokeWidthAttributeName 配合NSStrokeColorAttributeName使用"];
[attrStr addAttribute: NSStrokeWidthAttributeName value: @(-2) range: NSMakeRange(0, attrStr.length)];
[attrStr addAttribute: NSStrokeColorAttributeName value: [UIColor blueColor] range: NSMakeRange(0, attrStr.length)];
- NSShadowAttributeName
設(shè)置陰影屬性慧库,取值為 NSShadow 對(duì)象跷跪。默認(rèn)為 nil。
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSShadowAttributeName 豎直方向偏移 15"];
NSShadow * shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor grayColor];
shadow.shadowOffset = CGSizeMake(0, 15);
[attrStr addAttribute: NSShadowAttributeName value:shadow range: NSMakeRange(0, attrStr.length)];
- NSTextEffectAttributeName
設(shè)置文本特殊效果完沪,取值為 NSString 對(duì)象域庇,目前只有圖版印刷效果可用NSTextEffectLetterpressStyle嵌戈。
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSTextEffectAttributeName 模式NSTextEffectLetterpressStyle"];
[attrStr addAttribute: NSTextEffectAttributeName value:NSTextEffectLetterpressStyle range: NSMakeRange(0, attrStr.length)];
- NSAttachmentAttributeName
設(shè)置文本附件,取值為NSTextAttachment對(duì)象,常用于文字圖片混排
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSAttachmentAttributeName "];
NSTextAttachment * textAtt = [[NSTextAttachment alloc] init];
textAtt.image = [UIImage imageNamed:@"tag_d"];
textAtt.bounds = CGRectMake(0, 0, 44, 44);
NSAttributedString *attrStr2 = [NSAttributedString attributedStringWithAttachment: textAtt];
[attrStr insertAttributedString: attrStr2 atIndex: 6];
- NSLinkAttributeName
設(shè)置鏈接屬性覆积,對(duì)象是NSURL點(diǎn)擊后調(diào)用瀏覽器打開(kāi)指定URL地址
推薦一款非常好用的輪子 TTTAttributedLabel
UITextView *textView = [[UITextView alloc] init];
textView.scrollEnabled = NO;
textView.editable = NO;
textView.frame =cell.bounds;
textView.textContainer.lineFragmentPadding = 0;
textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
textView.delegate = self;
attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSLinkAttributeName 測(cè)試 百度"];
[attrStr addAttribute: NSLinkAttributeName value:[NSURL URLWithString: @"http://www.baidu.com"] range: NSMakeRange(0, attrStr.length)];
textView.attributedText = attrStr;
- NSBaselineOffsetAttributeName
設(shè)置基線偏移值,取值為 NSNumber (float),正值上偏熟呛,負(fù)值下偏
NSAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSBaselineOffsetAttributeName 偏移5"];
[attrStr addAttribute: NSBaselineOffsetAttributeName value: @(5) range: NSMakeRange(0, attrStr.length)];
- NSUnderlineColorAttributeName
設(shè)置下劃線顏色宽档,取值為 UIColor 對(duì)象,默認(rèn)值為黑色
NSAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSUnderlineColorAttributeName "];
[attrStr addAttribute: NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range: NSMakeRange(0, attrStr.length)];
[attrStr addAttribute: NSUnderlineColorAttributeName value:[UIColor yellowColor] range: NSMakeRange(0, attrStr.length)];
- NSStrikethroughColorAttributeName
設(shè)置刪除線顏色庵朝,取值為 UIColor 對(duì)象吗冤,默認(rèn)值為黑色
NSAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSStrikethroughColorAttributeName "];
[attrStr addAttribute: NSStrikethroughStyleAttributeName value:@(1) range: NSMakeRange(0, attrStr.length)];
[attrStr addAttribute: NSStrikethroughColorAttributeName value:[UIColor brownColor] range: NSMakeRange(0, attrStr.length)];
- NSObliquenessAttributeName
設(shè)置字形傾斜度,取值為 NSNumber (float),正值右傾九府,負(fù)值左傾
NSAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSStrikethroughColorAttributeName 右傾斜"];
[attrStr addAttribute: NSObliquenessAttributeName value:@(1) range: NSMakeRange(0, attrStr.length)];
- NSExpansionAttributeName
設(shè)置文本橫向拉伸屬性椎瘟,取值為 NSNumber (float),正值橫向拉伸文本,負(fù)值橫向壓縮
NSAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSExpansionAttributeName 橫向壓"];
[attrStr addAttribute: NSFontAttributeName value: [UIFont fontWithName: @"Papyrus" size: 12] range: NSMakeRange(0, attrStr.length)];
[attrStr addAttribute: NSExpansionAttributeName value:@(1) range: NSMakeRange(0, attrStr.length)];
- NSWritingDirectionAttributeName
設(shè)置文字書(shū)寫(xiě)方向侄旬,取值為以下組合
@[@(NSWritingDirectionLeftToRight|NSWritingDirectionEmbedding)];
@[@(NSWritingDirectionRightToLeft|NSWritingDirectionEmbedding)];
@[@(NSWritingDirectionLeftToRight|NSWritingDirectionOverride)];
@[@(NSWritingDirectionRightToLeft|NSWritingDirectionOverride)];
NSAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSWritingDirectionAttributeName 方式NSWritingDirectionLeftToRight&Embedding"];
[attrStr addAttribute: NSWritingDirectionAttributeName value:@[@(NSWritingDirectionLeftToRight | NSWritingDirectionEmbedding)] range: NSMakeRange(0, attrStr.length)];
- NSVerticalGlyphFormAttributeName
文本方向肺蔚,取值為 NSNumber 對(duì)象(整數(shù))。0 表示橫排文本儡羔。1 表示豎排文本宣羊。在 iOS 中,總是使用橫排文本汰蜘,0 以外的值都未定義仇冯。
NSAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是NSVerticalGlyphFormAttributeName "];
[attrStr addAttribute: NSVerticalGlyphFormAttributeName value:@(0) range: NSMakeRange(0, attrStr.length)];
- NSDocumentTypeDocumentAttribute
直接進(jìn)行 html 的展示
NSString * htmlString = @"<html><body> Some html string \n <font size=\"13\" color=\"red\">This is some text!This is some text!This is some text!This is some text!This is some text!</font> </body></html>";
attrStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
三、關(guān)于計(jì)算
1 .在7.0以后官方計(jì)算的API
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
參數(shù)
size:
寬高限制族操,用于計(jì)算文本繪制時(shí)占據(jù)的矩形塊苛坚。
options:
文本繪制時(shí)的附加選項(xiàng)∩眩可能取值請(qǐng)參考“NSStringDrawingOptions”泼舱。
attributes:
文本繪制時(shí)用到的AttributedString的屬性,就是文中提到的20幾種莱预。
context:
context上下文柠掂。包括一些信息,例如如何調(diào)整字間距以及縮放依沮。最終涯贞,該對(duì)象包含的信息將用于文本繪制枪狂。該參數(shù)一般為 nil 。
返回值:
一個(gè)矩形宋渔,大小等于文本繪制完將占據(jù)的寬和高州疾。
具體計(jì)算方式,example
-(CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width
{
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.alignment = NSTextAlignmentLeft;
paraStyle.lineSpacing = 4;
NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle
};
CGSize size = [str boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
return size.height;
}
2 .計(jì)算真實(shí)的大小,sizeThatFits
- (CGSize)sizeThatFits:(CGSize)size; // return 'best' size to fit given size. does not actually resize view. Default is return existing view size
3 . 自適應(yīng)皇拣,sizeToFit
- (void)sizeToFit; // calls sizeThatFits: with current view bounds and changes bounds size.
視具體情況而定严蓖,靈活應(yīng)用上面三種方式計(jì)算即可,滿足絕大多數(shù)需求氧急。
附:NSParagraphStyle的屬性參考
屬性 | 解讀 |
---|---|
lineSpacing | CGFloat類(lèi)型颗胡,行距 |
paragraphSpacing | CGFloat類(lèi)型,段距 |
alignment | NSTextAlignment吩坝,對(duì)齊方式 |
firstLineHeadIndent | CGFloat類(lèi)型毒姨,首行縮進(jìn) |
headIndent | CGFloat類(lèi)型,縮進(jìn) |
tailIndent | CGFloat類(lèi)型钉寝,尾部縮進(jìn) |
lineBreakMode | CGFloat類(lèi)型弧呐,斷行方式 |
minimumLineHeight | CGFloat類(lèi)型,最小行高 |
maximumLineHeight | CGFloat類(lèi)型嵌纲,最大行高 |
baseWritingDirection | NSWritingDirection俘枫,句子方向 |
lineHeightMultiple | CGFloat類(lèi)型,可變行高,乘因數(shù) |
paragraphSpacingBefore | CGFloat類(lèi)型逮走,段首空間 |
hyphenationFactor | CGFloat類(lèi)型鸠蚪,連字符屬性 |
照例放Demo,僅供參考
Demo地址:
https://github.com/yongliangP/AttributedStringDemo
如果你覺(jué)得對(duì)你有幫助請(qǐng)點(diǎn)喜歡哦言沐,也可以關(guān)注我邓嘹,每周至少一篇技術(shù)。
或者關(guān)注 我的專(zhuān)題 每周至少5篇更新险胰,多謝支持哈汹押。