關(guān)鍵字高亮, 實(shí)際上就是對(duì)富文本的操作, 富文本的屬性大致如下:
陰影
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowBlurRadius = 1.0;// 模糊程度
shadow.shadowColor = [UIColor grayColor];
shadow.shadowOffset = CGSizeMake(1, 3);
NSFontAttributeName 字體
NSKernAttributeName 字間距[NSNumber]
NSParagraphStyleAttributeName 段落 [NSParagraphStyle ]
NSBackgroundColorAttributeName 背景色
NSForegroundColorAttributeName 字體色
NSLigatureAttributeName 連字符[NSNumber 0 表示沒(méi)有連體字符 1 默認(rèn)的連體字符 2表示使用所有連體符 默認(rèn)值為1]
NSUnderlineStyleAttributeName 下劃線
NSStrikethroughStyleAttributeName 刪除線[不指定的情況下刪除線顏色即為字體色]
NSShadowAttributeName 陰影 [創(chuàng)建NSShadow設(shè)置其偏移量(CGSizeMake)顏色及模糊程度 要配合下面3個(gè)使用]
NSObliquenessAttributeName 斜體
NSExpansionAttributeName 扁平化
NSVerticalGlyphFormAttributeName [整數(shù)0為橫排文本 1為豎排文本]
NSStrokeColorAttributeName 描邊顏色 [同時(shí)設(shè)置描邊屬性 之前的字體色失效]
NSStrokeWidthAttributeName 描邊寬度 [小數(shù)默認(rèn)為0為負(fù)數(shù)時(shí)改變描邊和填充寬度 對(duì)于空心字 通常為3.0]
我們經(jīng)常把富文本的屬性功能放到一個(gè)字典中:
NSDictionary *dicA = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20], // 字體
NSForegroundColorAttributeName:[UIColor blackColor], // 字體色
NSKernAttributeName:@5.0, // 字間距
NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle), // 刪除線
NSStrokeColorAttributeName:[UIColor blueColor], // 描邊顏色
NSStrokeWidthAttributeName:@2.0,
NSVerticalGlyphFormAttributeName:@(0)};
對(duì)一個(gè)關(guān)鍵字進(jìn)行富文本屬性賦值:
//設(shè)置關(guān)鍵字屬性
- (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range;
舉一個(gè)我做項(xiàng)目時(shí)候的例子(前方高能上圖)
當(dāng)前多少直播那里就是富文本的一種用法
代碼我就簡(jiǎn)單實(shí)現(xiàn)一下:
// 先創(chuàng)建一個(gè) UILabel 它的 frame 隨意給就好
UILabel *liveContent = [[UILabel alloc] initWithFrame:CGRectMake(180, 0, 300, 30)];
// 給字體設(shè)置個(gè)顏色
liveContent.textColor = [UIColor grayColor];
// 根據(jù)想要改變的位置, 先給出一個(gè)改變位置的字符串, 比如我這里需要的是數(shù)字
NSString *count = @"3984";
// 給文本一個(gè)內(nèi)容
liveContent.text = [NSString stringWithFormat:@"當(dāng)前%@個(gè)直播, 進(jìn)去看看", count];
// 創(chuàng)建富文本 (可變的) NSMutableAttributedString 并把想要修改的原字符串填入
NSMutableAttributedString *temp = [[NSMutableAttributedString alloc] initWithString:liveContent.text];
// 獲取改變部分在原字符串中的位置
NSRange range = [liveContent.text rangeOfString:count];
// 設(shè)置富文本屬性(切記字典的最后一組屬性, 不要有逗號(hào))
NSDictionary *dicA = @{
NSFontAttributeName:[UIFont boldSystemFontOfSize:20],
NSForegroundColorAttributeName:[UIColor colorWithRed:255.0/255.0 green:115.0/255.0 blue:156.0/255.0 alpha:255.0/255.0]
};
// 添加屬性到相應(yīng)位置
[temp setAttributes:dicA range:range];
// 將富文本給 label 的 attibutedText 屬性, 這里用的是賦值符號(hào)=給予的
liveContent.attributedText = attributedString;
PS: 只有單一屬性的話, 沒(méi)有必要寫(xiě)成字典
// 可以直接用 addAttribute: value: 這個(gè)方法添加單一屬性
[temp addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:255.0/255.0 green:115.0/255.0 blue:156.0/255.0 alpha:255.0/255.0] range:range];
// 賦值寫(xiě)法不一, 看個(gè)人喜好, 這里再給出一個(gè) KVC 的方式賦值
[liveContent setValue:temp forKey:@"attributedText"];