1. 程式人生 > >將且僅將UILabel上的所有數字變色指定的字體顏色<轉>

將且僅將UILabel上的所有數字變色指定的字體顏色<轉>

截取 @property elf range 設置 變色 其他 天藍色 all

先提出一個場景,一個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;

將且僅將UILabel上的所有數字變色指定的字體顏色<轉>