先提出一個場景,一個UILabel上面有各種數字字元中文字元以及字母等,現在我們想将其中的數字找出來并且變為和其他字元不同的顔色。
這裡提出一個解決方法,通過for循環來截取一個一個字元,判斷其是不是0-9的數字,如果是就設定他的字型屬性,我們使用了 NSMutableAttributedString實作富文本(帶屬性的字元串)。
NSAttributedString的使用方法,跟NSMutableString,NSString類似
1.使用方法:
為某一範圍内文字設定多個屬性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
為某一範圍内文字添加某個屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
為某一範圍内文字添加多個屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
移除某範圍内的某個屬性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
2. 常見的屬性及說明
NSFontAttributeName 字型
NSParagraphStyleAttributeName 段落格式
NSForegroundColorAttributeName 字型顔色
NSBackgroundColorAttributeName 背景顔色
NSStrikethroughStyleAttributeName删除線格式
NSUnderlineStyleAttributeName 下劃線格式
NSStrokeColorAttributeName 删除線顔色
NSStrokeWidthAttributeName删除線寬度
NSShadowAttributeName 陰影
//PS:下劃線屬性的設定方法
//[attributeString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(i, 1)];
那麼進入正題!,首先我們建立好UILabel,然後通過for循環來查找符合條件的數字
@property (nonatomic,strong)UILabel *myLabel;
self.myLabel = [[UILabelalloc]initWithFrame:CGRectMake(0,0, 375,100)];
self.myLabel.backgroundColor = [UIColorcyanColor];//天藍色背景
self.myLabel.textAlignment =1;//居中
[self.viewaddSubview:self.myLabel];
//這是我們的測試用的文本字元串資料
NSString *content = @"abc123a1b2c3你懂得888";
NSArray *number = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:content];
for (int i = 0; i < content.length; i ++) {
//這裡的小技巧,每次隻截取一個字元的範圍
NSString *a = [content substringWithRange:NSMakeRange(i, 1)];
//判斷裝有0-9的字元串的數字數組是否包含截取字元串出來的單個字元,進而篩選出符合要求的數字字元的範圍NSMakeRange
if ([number containsObject:a]) {
[attributeString setAttributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:[UIFont systemFontOfSize:25],NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(i, 1)];
}
}
//完成查找數字,最後将帶有字型下劃線的字元串顯示在UILabel上
self.myLabel.attributedText = attributeString;