前言
iOS中Label是我們經常遇到的一個控件,我們大家應該都會簡單的使用它,像下面這個代碼,就能簡單的創建一個label
// 1、創建CGRectrect =CGRectMake(100,100,100,100);UILabel* label = [[UILabelalloc]initWithFrame:rect];
引言
然而我們在開發中,經常會遇到一行字,但是顯示不同顏色和字體的情況,話不多說,直接上代碼。
1、顯示不同顏色,有兩種方式
(1)通過 range 來設置
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"點擊代表您已閱讀并同意用戶規則和協議"];[str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0,11)];[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(11,4)];[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(16,2)];label.attributedText = str;
(2)通過文字來設置
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"點擊代表您已閱讀并同意用戶規則和協議"];NSRange range1 = [[str string] rangeOfString:@"點擊代表您已閱讀并同意"];[str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:range1];NSRange range2 = [[str string] rangeOfString:@"用戶規則"];[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];NSRange range3 = [[str string] rangeOfString:@"協議"];[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range3];label.attributedText = str;
以上兩種的效果一樣,如圖:
2、顯示不同字體,也是兩種方式
(1)通過 range 來設置
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:13.0] range:NSMakeRange(0, 11)];[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0] range:NSMakeRange(11, 4)];[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:14.0] range:NSMakeRange(16, 2)];label.attributedText = str;
(2)通過文字來設置
NSRange range1 = [[str string] rangeOfString:@"點擊代表您已閱讀并同意"];[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:13.0] range:range1];NSRange range2 = [[str string] rangeOfString:@"用戶規則"];[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0] range:range2];NSRange range3 = [[str string] rangeOfString:@"協議"];[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:14.0] range:range3];label.attributedText = str;
以上兩種方式效果圖如下:
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答