NSAttributedString - 屬性字符串(富文本)
一種字符串,它的部分文本具有相關(guān)的樣式屬性(如視覺樣式棚瘟、超鏈接或輔助功能數(shù)據(jù))郁副。
NSAttributedString對象管理字符串和應(yīng)用于字符串中單個字符或字符范圍的相關(guān)屬性集(例如,字體和字距)页徐。字符及其屬性的關(guān)聯(lián)稱為屬性字符串苏潜。集群的兩個公共類NSAttributedString和NSMutableAttributedString分別聲明只讀屬性字符串和可修改屬性字符串的編程接口。
屬性字符串按照名稱標識屬性变勇,使用NSDictionary對象在給定名稱下存儲值恤左。可以將任何想要的屬性名/值對分配給一系列字符搀绣,由應(yīng)用程序來解釋自定義屬性(請參閱屬性字符串編程指南)飞袋。如果在CoreText框架(用來做文字處理的框架)中使用屬性字符串,也可以使用該框架定義的屬性Key链患。
可以將屬性字符串與接受它們的任何api(如Core Text)一起使用巧鸭。AppKit和UIKit框架還提供了NSMutableAttributedString的一個子類,稱為NSTextStorage麻捻,為擴展文本處理系統(tǒng)提供存儲纲仍。在iOS 6和更高版本中,可以使用屬性化字符串在UITextView贸毕、UITextField和一些其他控件中顯示格式化文本郑叠。AppKit和UIKit還定義了基本屬性字符串接口的擴展,該接口允許在當前圖形上下文中繪制它們的內(nèi)容明棍。
NSAttributedString對象的默認字體是Helvetica 12 point乡革,這可能與平臺的默認系統(tǒng)字體不同,因此為了適合應(yīng)用程序可能需要創(chuàng)建非默認屬性的新字符串。還可以使用NSParagraphStyle類及其子類NSMutableParagraphStyle封裝NSAttributedString類使用的段落或標尺屬性沸版。
注意嘁傀,使用isEqual:方法比較NSAttributedString對象會尋找完全相等的值,比較包括逐個字符串的相等檢查和所有屬性的相等檢查视粮。如果字符串具有許多屬性(例如附件细办、列表和表),則這樣的比較不太可能產(chǎn)生匹配馒铃。
NSAttributedString常用屬性
@property (readonly, copy) NSString *string;
屬性描述 : 作為調(diào)用方的字符內(nèi)容的NSString對象蟹腾。
NSAttributedString常用函數(shù)
- (NSDictionary<NSAttributedStringKey, id> *)attributesAtIndex:(NSUInteger)location effectiveRange:(nullable NSRangePointer)range;
函數(shù)描述:返回給定索引處字符的樣式屬性字典。如果索引超出調(diào)用方字符的結(jié)尾区宇,則引發(fā)NSRangeException娃殖。
參數(shù) :
index:要返回其屬性的索引,此值必須在調(diào)用方的范圍內(nèi)议谷。
range:對NSRange結(jié)構(gòu)體的引用炉爆,如果結(jié)構(gòu)體為NULL且指定的索引處應(yīng)用了樣式屬性,則在返回時aRange包含樣式屬性覆蓋的范圍卧晓,如果指定的索引處沒有應(yīng)用樣式屬性芬首,則在返回時aRange包含未應(yīng)用樣式屬性的覆蓋范圍。此范圍不一定是覆蓋的最大范圍逼裆,其范圍取決于實現(xiàn)郁稍。如果需要最大范圍,請使用attributesAtIndex:longestEffectiveRange:inRange:函數(shù)胜宇。如果不需要此值耀怜,請傳遞NULL。
返回值:索引處字符的屬性桐愉。
NSAttributedString (NSExtendedAttributedString) - 分類對屬性字符串的擴展
NSAttributedString (NSExtendedAttributedString) 常用屬性
@property (readonly) NSUInteger length;
屬性描述:調(diào)用方字符串對象的長度财破。
NSAttributedString (NSExtendedAttributedString) 常用函數(shù)
- (nullable id)attribute:(NSAttributedStringKey)attrName atIndex:(NSUInteger)location effectiveRange:(nullable NSRangePointer)range;
函數(shù)描述:返回在給定索引處與給定樣式屬性名稱綁定的樣式屬性的值,并通過對NSRange結(jié)構(gòu)體的引用返回該屬性樣式應(yīng)用的范圍从诲。
參數(shù):
attrName : 樣式屬性名稱左痢。
location:要返回其樣式屬性值的索引。此值不能超過調(diào)用方的邊界系洛,如果索引超出調(diào)用方字符的結(jié)尾俊性,則引發(fā)NSRangeException。
range:對NSRange結(jié)構(gòu)體的引用碎罚,如果結(jié)構(gòu)體為NULL且給定的樣式屬性名稱存在于索引磅废,則在返回時aRange包含與該樣式屬性名稱綁定的屬性值的范圍。如果指定的索引中不存在給定的樣式屬性名稱荆烈,則在返回時aRange包含與該樣式屬性名稱綁定的的屬性值不存在的范圍。范圍不一定是與attributeName參數(shù)綁定的屬性值覆蓋的最大范圍,它的范圍依賴于實現(xiàn)憔购。如果需要最大范圍宫峦,使用atIndex:longestEffectiveRange:inRange:函數(shù)。如果不需要此值玫鸟,則傳遞NULL导绷。
返回值:在指定索引位置且與樣式屬性名稱綁定的屬性的值,如果沒有這樣的屬性屎飘,則為nil妥曲。
- (NSAttributedString *)attributedSubstringFromRange:(NSRange)range;
函數(shù)描述 :返回在調(diào)用方中給定范圍內(nèi)的字符和屬性組成的NSAttributedString對象。如果aRange的任何部分超出了調(diào)用方字符的末尾钦购,則引發(fā)NSRangeException檐盟。
參數(shù):
range:創(chuàng)建新屬性字符串的范圍,range必須位于調(diào)用方的范圍內(nèi)押桃。
返回值:一個NSAttributedString對象葵萎,在調(diào)用方中截取range范圍中的字符和屬性組成。
- (NSDictionary<NSAttributedStringKey, id> *)attributesAtIndex:(NSUInteger)location longestEffectiveRange:(nullable NSRangePointer)range inRange:(NSRange)rangeLimit;
函數(shù)描述:返回給定索引處字符的屬性唱凯,并通過對NSRange結(jié)構(gòu)體的引用返回屬性應(yīng)用的范圍羡忘。如果索引或rangeLimit的任何部分超出調(diào)用方字符的結(jié)尾,則引發(fā)NSRangeException磕昼。如果不需要范圍信息卷雕,那么使用attributesAtIndex:effectiveRange:方法來檢索屬性值要有效得多。
參數(shù) :
location : 要返回其屬性的索引票从。此值不能超過調(diào)用方的邊界漫雕。
range:如果非空,則返回時包含樣式名稱和樣式值與索引處的樣式名稱和樣式值相同的最大范圍纫骑,剪裁為rangeLimit蝎亚。
rangeLimit:在索引處搜索屬性連續(xù)存在的范圍。此值不能超過調(diào)用方的邊界先馆。
- (nullable id)attribute:(NSAttributedStringKey)attrName atIndex:(NSUInteger)location longestEffectiveRange:(nullable NSRangePointer)range inRange:(NSRange)rangeLimit;
函數(shù)描述:返回在給定索引處與給定樣式屬性名稱綁定的樣式屬性的值发框,并通過對NSRange結(jié)構(gòu)體的引用返回該屬性樣式應(yīng)用的范圍。如果索引或rangeLimit的任何部分超出調(diào)用方字符的結(jié)尾煤墙,則引發(fā)NSRangeException梅惯。如果不需要范圍信息,那么使用attributesAtIndex:effectiveRange:方法來檢索屬性值要有效得多仿野。
參數(shù) :
attributeName:樣式屬性名稱铣减。
location:要返回其樣式屬性值的索引。此值不能超過調(diào)用方的邊界脚作,如果索引超出調(diào)用方字符的結(jié)尾葫哗,則引發(fā)NSRangeException缔刹。
range:對NSRange結(jié)構(gòu)體的引用,如果結(jié)構(gòu)體為NULL且給定的樣式屬性名稱存在于索引劣针,則在返回時aRange包含與該樣式屬性名稱綁定的屬性值的范圍校镐,并剪裁為rangeLimit。如果指定的索引中不存在給定的樣式屬性名稱捺典,則在返回時aRange包含與該樣式屬性名稱綁定的的屬性值不存在的范圍鸟廓,并剪裁為rangeLimit。如果不需要此值襟己,請傳遞NULL引谜。
rangeLimit:搜索attributeName的連續(xù)存在的范圍。此值不能超過調(diào)用方的邊界擎浴。
返回值:在指定索引位置且與樣式屬性名稱綁定的屬性的值员咽,如果沒有這樣的屬性,則為nil退客。
- (BOOL)isEqualToAttributedString:(NSAttributedString *)other;
函數(shù)描述:返回一個布爾值骏融,該值指示調(diào)用方是否等于另一個給定的屬性字符串。屬性字符串必須在字符和屬性中都匹配才能相等萌狂。
參數(shù) :
other:用來比較調(diào)用方的屬性字符串档玻。
返回值:如果調(diào)用方等于other,則為“YES”茫藏,否則為“NO”误趴。
- (instancetype)initWithString:(NSString *)str;
函數(shù)描述 :返回一個NSAttributedString對象,該對象由給定字符串的字符進行初始化务傲,沒有屬性信息凉当。
參數(shù) :
str : 初始化新對象的字符串。
返回值:用str字符初始化的NSAttributedString對象售葡,返回的對象可能與原始調(diào)用方不同看杭,并且沒有屬性信息。
- (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSAttributedStringKey, id> *)attrs;
函數(shù)描述:返回用給定字符串和樣式屬性初始化的NSAttributedString對象挟伙。返回一個NSAttributedString對象楼雹,用str的字符串和attrs中的屬性初始化。返回的對象可能與原始調(diào)用方不同尖阔。
參數(shù) :
str:初始化新屬性字符串的字符串贮缅。
attrs:新屬性字符串的屬性。
返回值 : 返回用給定字符串和屬性初始化的NSAttributedString對象介却。
- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;
函數(shù)描述:返回使用另一個給定屬性字符串的字符和屬性初始化的NSAttributedString對象谴供。
參數(shù):
attrStr : 屬性字符串。
返回值:用attributedString的字符和屬性初始化的NSAttributedString對象齿坷。返回的對象可能與原始調(diào)用方不同桂肌。
- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(NSDictionary<NSAttributedStringKey, id> *attrs, NSRange range, BOOL *stop))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
函數(shù)描述 :在調(diào)用方枚舉屬性的范圍內(nèi)数焊,為屬性字符串中的每個屬性范圍執(zhí)行指定的塊。如果此方法由NSMutableAttributedString的實例調(diào)用轴或,則僅當改變在提供給塊的范圍內(nèi)時昌跌,才允許進行改變(刪除仰禀、添加或更改)照雁。改變后,枚舉繼續(xù)進行答恶,范圍緊跟在處理過的范圍之后饺蚊,根據(jù)改變引起的長度變化進行調(diào)整。例如悬嗓,如果使用從位置N開始的范圍調(diào)用塊污呼,并且該塊刪除所提供范圍中的所有字符,則下一次調(diào)用也將傳遞N作為范圍的位置包竹。
參數(shù) :
enumerationRange:調(diào)用方枚舉屬性的范圍燕酷。
opts:枚舉使用的選項。
block:應(yīng)用于屬性字符串中屬性范圍的塊周瞎。該塊有三個參數(shù):
- attrs:按名稱鍵入的屬性值字典苗缩。
- range:屬性字符串中屬性值的范圍。
- stop:對布爾值的引用声诸。塊可以在塊內(nèi)將值設(shè)置為YES酱讶,以停止對屬性字符串的進一步處理。
遍歷的次數(shù)根據(jù)調(diào)用方枚舉屬性的范圍內(nèi)彼乌,根據(jù)應(yīng)用樣式屬性的范圍進行拆分泻肯,如圖,圖中的字符串在枚舉范圍全覆蓋的情況下慰照,會執(zhí)行三次循環(huán):
- (void)enumerateAttribute:(NSAttributedStringKey)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(id _Nullable value, NSRange range, BOOL *stop))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
函數(shù)描述 :在調(diào)用方枚舉屬性的范圍內(nèi)灶挟,為屬性字符串中的每個屬性范圍執(zhí)行指定的塊并枚舉指定樣式屬性名稱的樣式屬性值。如果此方法由NSMutableAttributedString的實例調(diào)用毒租,則僅當改變在提供給塊的范圍內(nèi)時稚铣,才允許進行改變(刪除、添加或更改)蝌衔。改變后榛泛,枚舉繼續(xù)進行,范圍緊跟在處理過的范圍之后噩斟,根據(jù)改變引起的長度變化進行調(diào)整曹锨。例如,如果使用從位置N開始的范圍調(diào)用塊剃允,并且該塊刪除所提供范圍中的所有字符沛简,則下一次調(diào)用也將傳遞N作為范圍的位置齐鲤。
參數(shù) :
attrName : 要枚舉的樣式屬性的名稱。
opts:枚舉屬性值的范圍椒楣。
block:應(yīng)用于屬性字符串中指定屬性的范圍的塊给郊。該塊有三個參數(shù):
- value:指定屬性的值。
- range:屬性字符串中屬性值的范圍捧灰。
- stop:對布爾值的引用淆九。塊可以在塊內(nèi)將值設(shè)置為YES,以停止對屬性字符串的進一步處理毛俏。
//屬性值的范圍提供的枚舉方式:
typedef NS_OPTIONS(NSUInteger, NSAttributedStringEnumerationOptions) {
//使枚舉反向發(fā)生炭庙。
NSAttributedStringEnumerationReverse = (1UL << 1),
//如果提供NSAttributedStringEnumerationLongestEffectiveRangeNotRequired選項,
//則不執(zhí)行最長有效范圍計算煌寇;可以使用具有相同值的連續(xù)屬性運行來調(diào)用塊焕蹄。
NSAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL << 20)
};
NSAttributedString (NSAttributedStringDocumentFormats) - 文檔格式分類
常用函數(shù)
- (nullable instancetype)initWithData:(NSData *)data options:(NSDictionary<NSAttributedStringDocumentReadingOptionKey, id> *)options documentAttributes:(NSDictionary<NSAttributedStringDocumentAttributeKey, id> * __nullable * __nullable)dict error:(NSError **)error API_AVAILABLE(macos(10.0), ios(7.0));
函數(shù)描述 :初始化給定數(shù)據(jù)對象中包含的數(shù)據(jù)并返回新的屬性字符串對象。不應(yīng)從后臺線程調(diào)用HTML導(dǎo)入器(即阀溶,選項字典包含值為 NSHTMLTextDocumentType 的 NSDocumentTypeDocumentAttribute)腻脏,它將嘗試與主線程同步,失敗并超時银锻。從主線程調(diào)用它是有效的(但如果 HTML 包含對外部資源的引用永品,仍然會超時,應(yīng)該不惜一切代價避免這種情況)徒仓。 HTML導(dǎo)入機制旨在實現(xiàn)諸如markdown之類的東西(即文本樣式腐碱、顏色等),而不是用于一般的HTML導(dǎo)入掉弛。
參數(shù) :
data : 從中創(chuàng)建字符串的數(shù)據(jù)症见。
options :用于解釋文檔內(nèi)容的文檔屬性。支持選項鍵包括NSDocumentTypeDocumentAttribute殃饿、NSCharacterEncodingDocumentAttribute和NSDefaultAttributesDocumentAttribute谋作。如果傳遞空字典,則該方法將檢查數(shù)據(jù)以嘗試確定適當?shù)膶傩浴?/p>
dict : 包含文檔屬性中描述的文檔級屬性的輸入輸出字典乎芳∽裱粒可以為空,在這種情況下不返回文檔屬性奈惑。
error : 一個輸入輸出變量吭净,包含遇到的錯誤(如果有的話)。
NSAttributedStringDocumentAttributeKey - 應(yīng)用于文檔的屬性枚舉
typedef NSString * NSAttributedStringDocumentAttributeKey NS_TYPED_EXTENSIBLE_ENUM;
類型描述 : 應(yīng)用于文檔的屬性枚舉肴甸。
UIKIT_EXTERN NSAttributedStringDocumentAttributeKey const NSDocumentTypeDocumentAttribute API_AVAILABLE(macos(10.0), ios(7.0));
常量描述 : 這個屬性的值是NSAttributedStringDocumentType中聲明的一種文檔類型寂殉。對于reader(讀取)方法,選項中的這個鍵可以指定解釋內(nèi)容的文檔類型原在。在返回時友扰,文檔屬性可以包含此鍵彤叉,用于指示用于讀取內(nèi)容的實際格式。對于write(寫入)方法村怪,此鍵指定生成數(shù)據(jù)的格式秽浇。
UIKIT_EXTERN NSAttributedStringDocumentAttributeKey const NSCharacterEncodingDocumentAttribute API_AVAILABLE(macos(10.0), ios(7.0));
常量描述 : 此屬性的值是一個包含整數(shù)的NSNumber對象,指定文件的NSStringEncoding甚负,純文本的默認值是默認編碼柬焕。這個輸入選項可以指定reader(讀取)數(shù)據(jù)的字符串編碼。返回時腊敲,文檔屬性可以包含實際使用的編碼击喂。對于write(寫入)方法碰辅,此值用于生成純文本數(shù)據(jù)。
UIKIT_EXTERN NSAttributedStringDocumentAttributeKey const NSDefaultAttributesDocumentAttribute API_AVAILABLE(macos(10.11), ios(7.0));
常量描述 : 這個屬性的值是一個NSDictionary對象介时,它包含應(yīng)用于普通文件的屬性没宾。由reader方法使用凉蜂。選項中的這個鍵可以指定應(yīng)用于整個文檔內(nèi)容的默認屬性缨该。在返回時毫缆,文檔屬性可以包含這個鍵赔癌,指示實際使用的屬性荚虚。
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"TTTAttributedLabel";
NSString *htmlText = @"<a href=https://music.163.com/#/song?id=4900975>城南花已開</a>";
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectZero];
testLabel.font = [UIFont systemFontOfSize:15];
[self.view addSubview:testLabel];
[testLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
}];
testLabel.attributedText = [self handleHtmlText:htmlText];
}
- (NSMutableAttributedString *)handleHtmlText:(NSString *)htmlText{
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc]
initWithData:[htmlText dataUsingEncoding:
NSUnicodeStringEncoding]
options:@{
NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType,
}
documentAttributes:nil error:nil];
return attrStr;
}
@end
樣式如圖:
NSAttributedString (NSAttributedStringAttachmentConveniences) - 附件便利性分類
+ (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment API_AVAILABLE(macos(10.0), ios(7.0));
函數(shù)描述 : 創(chuàng)建帶有附件的屬性字符串疮胖,例如用于圖文混排溜嗜。這是使用NSAttachmentCharacter作為基字符創(chuàng)建包含附件的屬性字符串的方便方法火俄。
參數(shù) :
attachment :附件工三。
返回值 : 包含附件的屬性字符串迁酸。
這個代碼就有點長了俭正,首先需要一個UIImage的分類奸鬓,實現(xiàn)如下方法:
///繪制帶有文本、顏色掸读、圓角的圖片
+ (UIImage *)imageWithText:(NSString *)text font:(UIFont *)font fillColor:(CGColorRef)fillColor cornerRadius:(CGFloat)cornerRadius{
//返回使用指定字體所需要的邊框大小
CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:font}];
//設(shè)置圖片的框架矩形
textSize.width = 8.0 + ceil(textSize.width);
textSize.height = 2.0 + ceil(textSize.height) ;
CGRect imageFrame = {0, 0, textSize};
//創(chuàng)建基于位圖的圖形上下文并使其成為當前上下文串远。
UIGraphicsBeginImageContext(imageFrame.size);
//返回當前圖形上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//使用CGColor設(shè)置圖形上下文中的當前填充顏色
CGContextSetFillColorWithColor(context, fillColor);
//使用當前圖形狀態(tài)中的填充顏色繪制所提供矩形中包含的區(qū)域。
CGContextFillRect(context, imageFrame);
//根據(jù)當前基于位圖的圖形上下文的內(nèi)容返回圖像儿惫。
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//從堆棧頂部移除當前基于位圖的圖形上下文澡罚。
UIGraphicsEndImageContext();
//設(shè)置圖片圓角
UIImage *circleImage = [image setCornerRadius:cornerRadius];
UIImage *textImage = [circleImage addText:text withFont:font];
return textImage;
}
///設(shè)置圖片圓角
- (UIImage *)setCornerRadius:(CGFloat)cornerRadius {
//創(chuàng)建一個臨時渲染上下文,在這上面繪制原始圖片
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
//圖片的框架矩形
CGRect imageRect = {0, 0, self.size};
//創(chuàng)建并返回用圓角矩形路徑初始化的新UIBezierPath對象
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:imageRect cornerRadius:cornerRadius];
//將Path添加到上下文中
CGContextAddPath(UIGraphicsGetCurrentContext(), path.CGPath);
//裁剪上下文
CGContextClip(UIGraphicsGetCurrentContext());
//在指定的矩形中繪制整個圖像肾请,并根據(jù)需要進行縮放
[self drawInRect:imageRect];
//從當前環(huán)境當中得到重繪的圖片
UIImage *circleImag = UIGraphicsGetImageFromCurrentImageContext();
//從堆棧頂部移除當前基于位圖的圖形上下文留搔。
UIGraphicsEndImageContext();
//返回繪制的圖片
return circleImag;
}
///繪制指定字體的文本到圖片中
- (UIImage *)addText:(NSString *)text withFont:(UIFont *)font {
// 1.獲取上下文
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
// 2.繪制圖片
CGRect imageRect = {0, 0, self.size};
// 在指定的矩形中繪制整個圖像,并根據(jù)需要進行縮放
[self drawInRect:imageRect];
// 3.繪制文字
CGRect textRect = CGRectInset(imageRect, 2.0, 1.0);
// 段落樣式布局對象
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
// 文字對齊方式
style.alignment = NSTextAlignmentCenter;
// 文字的屬性
NSDictionary *attributes = @{NSFontAttributeName: font,
NSParagraphStyleAttributeName:style,
NSForegroundColorAttributeName:[UIColor whiteColor]};
// 將文字繪制上去
[text drawInRect:textRect withAttributes:attributes];
// 獲取繪制到得圖片
UIImage *textImage = UIGraphicsGetImageFromCurrentImageContext();
// 結(jié)束圖片的繪制
UIGraphicsEndImageContext();
// 返回繪制的圖片
return textImage;
}
然后在需要添加標簽的視圖中實現(xiàn)添加標簽的方法:
/// 帶標簽的富文本
/// @param labelContentArray 標簽內(nèi)容數(shù)組
/// @param labelColorArray 標簽顏色數(shù)組
/// @param contentString 要插入標簽的內(nèi)容
- (NSMutableAttributedString *)carryLabelOfAttributedStringWithLabelContentArray:(NSArray<NSString *> *)labelContentArray withLabelColorArray:(NSArray<UIColor *> *)labelColorArray withContentString:(NSString *)contentString{
//初始化要加入標簽的富文本
NSMutableAttributedString *contentAttributedString = [[NSMutableAttributedString alloc]initWithString:contentString];
//初始化用于存放轉(zhuǎn)為圖片對象的標簽內(nèi)容數(shù)組
NSMutableArray<UIImage *> *labelImages = [[NSMutableArray alloc] initWithCapacity:3];
//標簽內(nèi)容數(shù)組不為空
if(labelContentArray.count){
//標簽的圓角
CGFloat const cornerRadius = 3.0;
//標簽的字體
UIFont * const font = [UIFont systemFontOfSize:15.0 weight:UIFontWeightBold];
//記錄轉(zhuǎn)為標簽的圖片
UIImage *labelImage;
//遍歷標簽內(nèi)容數(shù)組
for (int i = 0; i < labelContentArray.count; i++) {
//獲取標簽內(nèi)容
NSString *labelContentString = labelContentArray[I];
//獲取標簽顏色
UIColor *labelColor = [UIColor blackColor];
if (labelColorArray.count) {
if (i < labelColorArray.count) {
labelColor = labelColorArray[I];
} else {
labelColor = labelColorArray.lastObject;
}
}
//標簽內(nèi)容不為空
if(labelContentString.length){
//獲取標簽圖片
labelImage = [UIImage imageWithText:labelContentString font:font fillColor:labelColor.CGColor cornerRadius:cornerRadius];
//如果標簽圖片不為空
if (labelImage) {
//添加標簽圖片到標簽圖片數(shù)組
[labelImages addObject:labelImage];
}
}
}
}else{
//返回要加入標簽的富文本
return contentAttributedString;
}
//遍歷標簽圖片數(shù)組
for (UIImage *image in labelImages.reverseObjectEnumerator.allObjects) {
//初始化文本與附件排版對象
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
//設(shè)置文本附件內(nèi)容的圖像
attachment.image = image;
//定義文本坐標系中調(diào)用方圖形表示的布局界限
attachment.bounds = CGRectMake(0, -3.0, image.size.width, image.size.height);
//初始化空格富文本對象
NSAttributedString *spaceString = [[NSAttributedString alloc] initWithString:@" "];
//每次循環(huán)先插入一個空格
[contentAttributedString insertAttributedString:spaceString atIndex:0];
//文本與附件排版對象轉(zhuǎn)為標簽富文本
NSAttributedString *labelContentAttribute = [NSAttributedString attributedStringWithAttachment:attachment];
//插入標簽富文本
[contentAttributedString insertAttributedString:labelContentAttribute atIndex:0];
}
//返回插入標簽富文本后的內(nèi)容
return contentAttributedString;
}
添加標簽:
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectZero];
testLabel.font = [UIFont systemFontOfSize:20];
testLabel.attributedText = [self carryLabelOfAttributedStringWithLabelContentArray:@[@"滿減",@"返現(xiàn)",@"顯示折扣"] withLabelColorArray:@[[UIColor redColor],[UIColor blueColor],[UIColor purpleColor]] withContentString:@"測試標簽文本"];
[self.view addSubview:testLabel];
testLabel.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
[testLabel.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
[testLabel.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor],
]];
NSMutableAttributedString - 可變屬性字符串(富文本)
一個可變字符串對象筐喳,它還包含與其文本內(nèi)容的各個部分相關(guān)聯(lián)的屬性(如視覺樣式催式、超鏈接或輔助功能數(shù)據(jù))函喉。
NSMutableAttributedString類聲明了用于改變屬性字符串內(nèi)容的其他方法∪僭拢可以單獨添加和刪除字符(原始字符串)和屬性管呵,也可以整體作為屬性字符串一起添加和刪除。
NSMutableAttributedString在NSAttributedString的基礎(chǔ)上增加了兩個原始方法哺窄,這些原始方法為其類中的所有其他方法提供了基礎(chǔ)捐下。原始的replaceCharactersInRange:withString:方法用字符串中的字符替換一系列字符,使該范圍之外的所有屬性信息保持不變萌业。原始setAttributes:range: 方法為給定的字符范圍設(shè)置屬性和值坷襟,替換該范圍的任何先前的屬性和值。
NSMutableAttributedString提供的函數(shù)
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;
函數(shù)描述 :用給定字符串的字符替換給定范圍內(nèi)的字符生年。新字符從range繼承第一個替換字符的樣式屬性婴程。如果range的長度為0,則新字符繼承range前面的字符(如果有的話)的樣式屬性抱婉,否則繼承range后面的字符的樣式屬性档叔。如果range的任何部分超出調(diào)用方字符的結(jié)尾,則引發(fā)NSRangeException蒸绩。
參數(shù) :
range : 指定要替換的字符的范圍衙四。
str : 一個字符串,指定替換range范圍內(nèi)的字符患亿。
- (void)setAttributes:(nullable NSDictionary<NSAttributedStringKey, id> *)attrs range:(NSRange)range;
函數(shù)描述 :將指定范圍內(nèi)字符的樣式屬性設(shè)置為指定的樣式屬性传蹈,這些新屬性替換以前與aRange中的字符關(guān)聯(lián)的任何樣式屬性。如果range的任何部分超出調(diào)用方字符的結(jié)尾步藕,則引發(fā)NSRangeException惦界。
參數(shù) :
attributes : 包含要設(shè)置的屬性的字典。屬性鍵可以由另一個框架提供漱抓,也可以是定義的自定義鍵表锻。
range:其屬性已設(shè)置的字符范圍。
NSMutableAttributedString (NSExtendedMutableAttributedString) - 擴展分類
- (void)addAttribute:(NSAttributedStringKey)name value:(id)value range:(NSRange)range;
函數(shù)描述 :將具有給定名稱和值的樣式屬性添加到指定范圍內(nèi)的字符乞娄,可以將任何希望的名稱/值對分配給一系列字符瞬逊。如果名稱或值為nil,則引發(fā)NSInvalidArgumentException仪或;如果range的任何部分超出了調(diào)用方字符的結(jié)尾确镊,則引發(fā)NSRangeException。
參數(shù) :
name : 指定屬性名的字符串范删。屬性鍵可以由另一個框架提供蕾域,也可以是定義的自定義鍵。
value : 與名稱關(guān)聯(lián)的屬性值。
range : 應(yīng)用指定屬性/值對的字符范圍旨巷。
- (void)addAttributes:(NSDictionary<NSAttributedStringKey, id> *)attrs range:(NSRange)range;
函數(shù)描述 :將給定的屬性集合添加到指定范圍內(nèi)的字符巨缘,可以將任何希望的名稱/值對分配給一系列字符。如果屬性為nil采呐,則引發(fā)NSInvalidArgumentException若锁;如果aRange的任何部分位于調(diào)用方字符的末尾之外,則引發(fā)NSRangeException斧吐。
參數(shù) :
attrs : 包含要添加的屬性的字典又固。屬性鍵可以由另一個框架提供,也可以是定義的自定義鍵煤率。
range : 應(yīng)用指定屬性的字符范圍仰冠。
- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString;
函數(shù)描述 :調(diào)用方將給定范圍內(nèi)的字符和屬性替換為參數(shù)給定屬性字符串的字符和屬性。如果range的任何部分超出調(diào)用方字符的結(jié)尾蝶糯,則引發(fā)NSRangeException洋只。
參數(shù) :
range : 替換的字符和屬性的范圍。
attrString : 屬性字符串裳涛,其字符和屬性替換指定范圍內(nèi)的字符和屬性木张。
- (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc;
函數(shù)描述 :將給定屬性字符串的字符和屬性插入到調(diào)用方中給定的索引處。新的字符和屬性從給定的索引開始端三,現(xiàn)有的字符和屬性從索引到調(diào)用方的末端將按屬性字符串的長度移動。如果索引超出調(diào)用方字符的結(jié)尾鹃彻,則引發(fā)NSRangeException郊闯。
參數(shù) :
attrString : 插入其字符和屬性的字符串。
loc : 插入字符和屬性的索引蛛株。
- (void)appendAttributedString:(NSAttributedString *)attrString;
函數(shù)描述 :將給定屬性字符串的字符和屬性添加到調(diào)用方的末尾团赁。
參數(shù) :
attrString : 添加字符和屬性的字符串。
- (void)deleteCharactersInRange:(NSRange)range;
函數(shù)描述 :刪除給定范圍內(nèi)的字符及其相關(guān)屬性谨履。如果aRange的任何部分超出調(diào)用方字符的結(jié)尾欢摄,則引發(fā)NSRangeException。
參數(shù):
range : 指定要刪除的字符的范圍笋粟。
- (void)setAttributedString:(NSAttributedString *)attrString;
函數(shù)描述 : 用給定屬性字符串的字符和屬性替換調(diào)用方的全部內(nèi)容怀挠。
參數(shù) :
attrString : 屬性字符串,其字符和屬性替換調(diào)用方中的字符和屬性害捕。
- (void)removeAttribute:(NSAttributedStringKey)name range:(NSRange)range;
函數(shù)描述 :從指定范圍內(nèi)的字符中刪除命名屬性绿淋。如果range的任何部分超出調(diào)用方字符的結(jié)尾,則引發(fā)NSRangeException尝盼。
參數(shù) :
name : 指定要刪除的屬性名的字符串吞滞。屬性鍵可以由另一個框架提供,也可以是定義的自定義鍵盾沫。
range :從中刪除指定屬性的字符范圍裁赠。
//需要引入#import<CoreText/CoreText.h>
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"TTTAttributedLabel";
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectZero];
NSAttributedString *attarbuteString = [[NSAttributedString alloc]initWithString:@"城南花已開" attributes:@{
(NSString *)kCTFontAttributeName:[UIFont systemFontOfSize:30],
}];
[self.view addSubview:testLabel];
[testLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
}];
testLabel.attributedText = NSAttributedStringByScalingFontSize(attarbuteString,0.5);
}
///按比例縮放屬性字符串字體大小
static inline NSAttributedString * NSAttributedStringByScalingFontSize(NSAttributedString *attributedString, CGFloat scale) {
//NSAttributedString轉(zhuǎn)NSMutableAttributedString
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
//為屬性字符串中特定屬性的每個范圍執(zhí)行指定的塊
[mutableAttributedString enumerateAttribute:(NSString *)kCTFontAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, BOOL * __unused stop) {
//獲取字體對象
UIFont *font = (UIFont *)value;
//如果存在字體對象
if (font) {
//聲明字體名稱變量
NSString *fontName;
//獲取字體的大小
CGFloat pointSize;
//字體對象是UIFont類
if ([font isKindOfClass:[UIFont class]]) {
//獲取字體名稱
fontName = font.fontName;
//獲取字體大小
pointSize = font.pointSize;
} else {
//通過CFStringRef對象轉(zhuǎn)為NSString獲取字體名稱
fontName = (NSString *)CFBridgingRelease(CTFontCopyName((__bridge CTFontRef)font, kCTFontPostScriptNameKey));
//獲取字體大小
pointSize = CTFontGetSize((__bridge CTFontRef)font);
}
//從指定范圍內(nèi)的字符中刪除字體屬性
[mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:range];
//設(shè)置給定名稱的新字體引用殿漠。
CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)fontName, floorf(pointSize * scale), NULL);
//將字體名稱和計算字體大小的值的屬性添加到指定范圍內(nèi)的字符
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)fontRef range:range];
//釋放CTFontRef對象
CFRelease(fontRef);
}
}];
//返回新的屬性字符串
return mutableAttributedString;
}
- (void)beginEditing;
函數(shù)描述 :由子類重寫以緩沖或優(yōu)化對調(diào)用方字符或?qū)傩缘囊幌盗懈?/strong>,直到它收到匹配的endEditing消息佩捞,在此消息上绞幌,它可以合并更改并通知任何觀察者它已更改∈Ъ猓可以嵌套beginEditing和endEditing消息對啊奄。
- (void)endEditing;
函數(shù)描述 : 由子類重寫,以合并自上一個beginEditing消息以來所做的更改掀潮,并將更改通知任何觀察者菇夸。
文本的預(yù)定義字符屬性Key - 樣式屬性的名稱Key
UIKIT_EXTERN NSAttributedStringKey const NSFontAttributeName API_AVAILABLE(macos(10.0), ios(6.0));
常量描述 : 這個屬性的值是一個UIFont對象,使用此屬性可更改文本范圍的字體仪吧。如果未指定此屬性庄新,則該字符串默認使用Helvetica 12 point(Neue)字體。
UIKIT_EXTERN NSAttributedStringKey const NSForegroundColorAttributeName API_AVAILABLE(macos(10.0), ios(6.0));
常量描述 : 此屬性的值是UIColor對象薯鼠,使用此屬性可以指定渲染期間文本的顏色择诈。如果未指定此屬性,則文本將呈現(xiàn)為黑色出皇。
UIKIT_EXTERN NSAttributedStringKey const NSBackgroundColorAttributeName API_AVAILABLE(macos(10.0),
常量描述 : 此屬性的值是UIColor對象羞芍,使用此屬性指定文本后面背景區(qū)域的顏色。如果未指定此屬性郊艘,則不會繪制背景色荷科。
UIKIT_EXTERN NSAttributedStringKey const NSLigatureAttributeName API_AVAILABLE(macos(10.0), ios(6.0));
常量描述 : 設(shè)置連體屬性,取值為NSNumber 對象(整數(shù))纱注,0 表示沒有連體字符畏浆,1 表示使用默認的連體字符。
UIKIT_EXTERN NSAttributedStringKey const NSKernAttributeName API_AVAILABLE(macos(10.0), ios(6.0));
常量描述 : 此屬性的值是包含浮點值的NSNumber對象狞贱。設(shè)定字符間距刻获,字距調(diào)整可防止特定字符之間出現(xiàn)不需要的空格,具體取決于字體瞎嬉。值0表示已禁用緊排蝎毡,此屬性的默認值為0。
UIKIT_EXTERN NSAttributedStringKey const NSUnderlineStyleAttributeName API_AVAILABLE(macos(10.0),
常量描述 : 此屬性的值是包含整數(shù)的NSNumber對象佑颇,并與NSUnderlineStyle中描述的常量之一相對應(yīng)顶掉。此值指示文本是否帶下劃線,此屬性的默認值為NSUnderlineStyleNone挑胸。
UIKIT_EXTERN NSAttributedStringKey const NSUnderlineColorAttributeName API_AVAILABLE(macos(10.0),
常量描述 : 設(shè)置下劃線顏色痒筒,此屬性的值是UIColor對象。默認值為nil。
UIKIT_EXTERN NSAttributedStringKey const NSStrokeColorAttributeName API_AVAILABLE(macos(10.0), ios(6.0));
常量描述 : 這個參數(shù)的值是一個UIColor對象簿透。如果它沒有定義(這是默認情況)移袍,它被假設(shè)為與NSForegroundColorAttributeName的值相同,否則它描述輪廓顏色老充。
UIKIT_EXTERN NSAttributedStringKey const NSStrokeWidthAttributeName API_AVAILABLE(macos(10.0), ios(6.0));
常量描述 : 此屬性的值是包含浮點值的NSNumber對象葡盗。此值表示更改筆劃寬度的量,并指定為字體點大小的百分比啡浊。指定0(默認值)不進行其他更改觅够,負值填充效果,正值中空效果巷嚣。
UIKIT_EXTERN NSAttributedStringKey const NSTextEffectAttributeName API_AVAILABLE(macos(10.10), ios(7.0));
常量描述 : 設(shè)置文本特殊效果喘先,取值為 NSString 對象,目前只有圖版印刷效果可用廷粒。
UIKIT_EXTERN NSAttributedStringKey const NSLinkAttributeName API_AVAILABLE(macos(10.0), ios(7.0));
常量描述 : 設(shè)置鏈接屬性窘拯,點擊后調(diào)用瀏覽器打開指定URL地址。不能在UILabel和UITextField使用坝茎,只能用UITextView來進行涤姊。
UIKIT_EXTERN NSAttributedStringKey const NSBaselineOffsetAttributeName API_AVAILABLE(macos(10.0),
常量描述 : 文本位置的垂直偏移。此屬性的值是一個NSNumber對象嗤放,包含一個浮點值思喊,該值指示字符與基線的偏移量(以點為單位)。默認值為0次酌,正值上偏搔涝,負值下偏。
UIKIT_EXTERN NSAttributedStringKey const NSObliquenessAttributeName API_AVAILABLE(macos(10.0), ios(7.0));
常量描述 : 此屬性的值是一個NSNumber對象和措,其中包含一個浮點值,指示要應(yīng)用于字形的傾斜蜕煌。默認值為0派阱,表示沒有傾斜,正值右傾斜纪,負值左傾贫母。
UIKIT_EXTERN NSAttributedStringKey const NSExpansionAttributeName API_AVAILABLE(macos(10.0), ios(7.0));
常量描述 : 此屬性的值是一個包含浮點值的NSNumber對象,設(shè)置文本橫向拉伸屬性盒刚,默認值為0腺劣,正值橫向拉伸文本,負值橫向壓縮文本因块。
UIKIT_EXTERN NSAttributedStringKey const NSWritingDirectionAttributeName API_AVAILABLE(macos(10.6), ios(7.0));
常量描述 : 此屬性的值是一個NSArray對象橘原,設(shè)置文字書寫方向,從左向右書寫或者從右向左書寫。
UIKIT_EXTERN NSAttributedStringKey const NSVerticalGlyphFormAttributeName API_AVAILABLE(macos(10.7), ios(6.0));
常量描述 : 此屬性的值是包含整數(shù)的NSNumber對象趾断。值0表示水平文本拒名,值1表示垂直文本。在iOS中芋酌,始終使用水平文本增显,并且未定義指定不同的值。
@implementation TestTTTAttributedLabelViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"TTTAttributedLabel";
NSString *termLabelText = @"距離成熟還有:30天";
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectZero];
testLabel.font = [UIFont systemFontOfSize:15];
[self.view addSubview:testLabel];
[testLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
}];
NSRange range = [termLabelText rangeOfString:@":"];
NSMutableAttributedString *attributedTermLabelText = [[NSMutableAttributedString alloc]initWithString:termLabelText];
[attributedTermLabelText addAttributes:@{
//文本字體
NSFontAttributeName : [UIFont systemFontOfSize:20],
//文本顏色
NSForegroundColorAttributeName:[UIColor redColor],
//文本背景色
NSBackgroundColorAttributeName : [UIColor greenColor],
//文本字間距
NSKernAttributeName:@(5.0),
//下劃線
NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle),
//下劃線顏色
NSUnderlineColorAttributeName : [UIColor blueColor],
//筆畫寬度
NSStrokeWidthAttributeName:@(3.5),
//文本特殊效果脐帝,目前只有圖版印刷效果可用
NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
//設(shè)置基線偏移值,正值上偏同云,負值下偏。
NSBaselineOffsetAttributeName:@(5.0),
//文本傾斜堵腹,正值右傾炸站,負值左傾
NSObliquenessAttributeName : @(-0.5),
//文本橫向拉伸,正值橫向拉伸文本,負值橫向壓縮文本秸滴。
NSExpansionAttributeName:@(0.5),
//設(shè)置文字書寫方向@[@(1)]從左到右武契,@[@(3)]從右到左
NSWritingDirectionAttributeName:@[@(3)],
} range:NSMakeRange(range.location + 1, termLabelText.length - (range.location + 2))];
testLabel.attributedText = attributedTermLabelText;
}
@end
樣式如圖 :
UIKIT_EXTERN NSAttributedStringKey const NSAttachmentAttributeName API_AVAILABLE(macos(10.0), ios(7.0));
常量描述 : 設(shè)置文本附件,取值為NSTextAttachment對象荡含,常用于文字圖片混排咒唆。
UIKIT_EXTERN NSAttributedStringKey const NSShadowAttributeName API_AVAILABLE(macos(10.0), ios(6.0));
常量描述 : 此屬性的值是NSShadow對象。此屬性的默認值為nil释液。表示與文本字體色相同全释。
UIKIT_EXTERN NSAttributedStringKey const NSStrikethroughStyleAttributeName API_AVAILABLE(macos(10.0),
常量描述 : 設(shè)置刪除線,此屬性的值是包含整數(shù)的NSNumber對象误债。此值指示文本是否有一條線穿過它浸船,并與NSUnderlineStyle中描述的常量之一相對應(yīng)。此屬性的默認值為NSUnderlineStyleNone寝蹈。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectZero];
label2.attributedText = [self attributeSingleLine:@"我被劃線了李命,要失業(yè)了"];
label2.textColor = [UIColor redColor];
label2.numberOfLines = 0;
label2.allowsDefaultTighteningForTruncation = NO;
[self.view addSubview:label2];
[label2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
make.left.equalTo(self.view.mas_left).offset(100);
make.right.equalTo(self.view.mas_right).offset(-100);
}];
}
///文本添加刪除線
- (NSAttributedString *)attributeSingleLine:(NSString *)str{
//富文本設(shè)置(刪除線)
NSMutableAttributedString *Att = [[NSMutableAttributedString alloc]initWithString:str];
NSUInteger length = [Att length];
[Att addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
return Att;
}
樣式如圖 :
UIKIT_EXTERN NSAttributedStringKey const NSStrikethroughColorAttributeName API_AVAILABLE(macos(10.0),
常量描述 : 設(shè)置刪除線顏色,此屬性的值是UIColor對象箫老。默認值為nil封字,表示與文本字體色相同。
UIKIT_EXTERN NSAttributedStringKey const NSParagraphStyleAttributeName API_AVAILABLE(macos(10.0),
常量描述 : 此屬性的值是NSParagraphStyle對象耍鬓。設(shè)置文本段落排版格式阔籽,如設(shè)置首行,行間距牲蜀,對齊方式等笆制。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectZero];
label2.attributedText = [self getAttributedWithString:@"測試標簽,內(nèi)容也挺多的,最起碼要能換個行吧涣达,要不怎么測試行間距呢在辆,沒辦法測試的啊" WithLineSpace:10 kern:10 font:[UIFont systemFontOfSize:18.0]];
label2.textColor = [UIColor redColor];
label2.numberOfLines = 0;
label2.allowsDefaultTighteningForTruncation = NO;
[self.view addSubview:label2];
[label2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
make.left.equalTo(self.view.mas_left).offset(100);
make.right.equalTo(self.view.mas_right).offset(-100);
}];
}
/**
調(diào)整文本間距
@parameter string 要調(diào)整的文本
@parameter lineSpace 行間距
@parameter kern 字符間距
@parameter font 字體
*/
- (NSAttributedString *)getAttributedWithString:(NSString *)string WithLineSpace:(CGFloat)lineSpace kern:(CGFloat)kern font:(UIFont *)font{
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
//調(diào)整行間距
paragraphStyle.lineSpacing = lineSpace;
NSDictionary *attriDict = @{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@(kern),
NSFontAttributeName:font};
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:string attributes:attriDict];
return attributedString;
}
樣式如圖 :
注:文本如果設(shè)置了間距证薇,那么計算文本高度時一定要將間距計算進去,否則會影響文本高度計算的結(jié)果开缎。例如計算這段文本:
不加間距的情況下:
CGSize size = [@"測試標簽,內(nèi)容也挺多的棕叫,最起碼要能換個行吧,要不怎么測試行間距呢奕删,沒辦法測試的啊" boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18.0],
}
context:nil].size;
NSLog(@"%f",size.height);
輸出高度為:
在標簽中顯示的實際文本高度為:
加上字符間距與行間距的情況下:
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineSpacing = 10;
CGSize size = [@"測試標簽,內(nèi)容也挺多的俺泣,最起碼要能換個行吧,要不怎么測試行間距呢完残,沒辦法測試的啊" boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 200, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18.0],
NSParagraphStyleAttributeName : paragraphStyle,
NSKernAttributeName:@(10),
}
context:nil].size;
NSLog(@"%f",size.height);
輸出高度則比較接近伏钠,為: