iOS之文本屬性Attributes的使用


1.NSKernAttributeName: @10 調整字句 kerning 字句調整

2.NSFontAttributeName : [UIFont systemFontOfSize:_fontSize] 設置字體

3.NSForegroundColorAttributeName :[UIColor redColor] 設置文字顏色

4.NSParagraphStyleAttributeName : paragraph 設置段落樣式

5.NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];

paragraph.alignment = NSTextAlignmentCenter;

6.NSBackgroundColorAttributeName: [UIColor blackColor] 設置背景顏色

7.NSStrokeColorAttributeName設置文字描邊顏色,需要和NSStrokeWidthAttributeName設置描邊寬度,這樣就能使文字空心.

NSStrokeWidthAttributeName這個屬性所對應的值是一個 NSNumber 對象(小數)。該值改變描邊寬度(相對於字體size 的百分比)。默認為 0,即不改變。正數只改變描邊寬度。負數同時改變文字的描邊和填充寬度。例如,對於常見的空心字,這個值通常為3.0。

同時設置了空心的兩個屬性,並且NSStrokeWidthAttributeName屬性設置為整數,文字前景色就無效果了

 

效果:

  

效果:

 

8. NSStrikethroughStyleAttributeName 添加刪除線,strikethrough刪除線

 

效果:

 

9. NSUnderlineStyleAttributeName 添加下划線

 

效果:

 

10. NSShadowAttributeName 設置陰影,單獨設置不好使,必須和其他屬性搭配才好使。

和這三個任一個都好使,NSVerticalGlyphFormAttributeName,NSObliquenessAttributeName,NSExpansionAttributeName

 

11.NSVerticalGlyphFormAttributeName

該屬性所對應的值是一個 NSNumber 對象(整數)。0 表示橫排文本。1 表示豎排文本。在 iOS 中,總是使用橫排文本,0 以外的值都未定義。

 

效果:

 

12. NSObliquenessAttributeName設置字體傾斜。Skew 斜

 

效果:

 

13. NSExpansionAttributeName 設置文本扁平化

 

效果:

 

在項目開發中,我們經常會遇到在這樣一種情形:在一個UILabel 使用不同的顏色或不同的字體來體現字符串,在iOS 6 以后我們可以很輕松的實現這一點,官方的API 為我們提供了UILabel類的attributedText, 使用不同顏色和不同字體的字符串,我們可以使用NSAttributedText 和 NSMutableAttributedText 類來實現。


現實代碼:

.h 文件

1 @interface ViewController : UIViewController
2 @property (nonatomic, strong) IBOutlet UILabel *attrLabel;
3 - (IBAction)next:(id)sender;
4 @end

.m文件 在viewDidLoad方法中添加以下代碼:

1 self.title = @"For iOS 6 & later";
2 NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];
3 [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];
4 [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];
5 [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];
6 [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];
7 [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0] range:NSMakeRange(6, 12)];
8 [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)];
9 attrLabel.attributedText = str;


效果圖:

如果想在iOS6.0以前版本實現這個效果,需要使用到一個第三方庫TTTAttributedLabel,同時還有導入CoreText.frame框架.


免責聲明!

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



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