ios設置UILabel中文字的不同顏色和字體字號


參考博客:http://blog.csdn.net/woaifen3344/article/details/38352099

       http://www.cnblogs.com/whyandinside/archive/2013/12/27/3493475.html

要使UILabel顯示不同的字體,需要設置其 attributedText屬性

該屬性是NSMutableAttributedString/NSAttributedString類型;

NSAttributedString是一個帶有屬性的字符串,通過該類可以靈活地操作和呈現多種樣式的文字數據。

NSAttributedString維護一個NSString,用來保存最原始的字符串,另有一個NSDictionary用來保存各個子串/字符的屬性。

 1 NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"小路旁 堆積太多葉落 風吹動你和我 剩下沙丘荒漠"];  

2 [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)]; //設置字體顏色

3 [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:30.0] range:NSMakeRange(0, 5)]; //設置字體字號和字體類別


4 UILabel *attrLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 320, 90)];
 5 attrLabel.attributedText = str;
6 attrLabel.numberOfLines = 0;


NSMakeRange(0, 5):第一個參數表示字符串中的第幾個字符開始,第二個參數表示長度;

在iOS6.0以前版本實現這個效果,需要使用到一個第三方庫TTTAttributedLabel,

CocoaPods安裝和使用教程:

http://code4app.com/article/cocoapods-install-usage

podFile:pod 'TTTAttributedLabel'

  TTTAttributedLabel *lab;

 [lab setText:str];

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM