1. 程式人生 > >iOS_NSAttributedString 的21種屬性詳細介紹(圖文混排)

iOS_NSAttributedString 的21種屬性詳細介紹(圖文混排)

說明:
NSAttributedString 可以非常方便的實現文字排版和圖文混排功能. 共有21中效果(API), 本文將較詳細的介紹21種的屬性的使用

注: 本部落格由@凡俊編寫, @Scott, @春雨 稽核, 若轉載此文章,請註明出處和作者

核心API:

類: NSAttributedString, NSMutableAttributedString
API:

/**
     * API:  Character Attributes , NSAttributedString 共有21個屬性
     *
     * 1. NSFontAttributeName
->設定字型屬性,預設值:字型:Helvetica(Neue) 字號:12 * * * 2. NSParagraphStyleAttributeName ->設定文字段落排版格式,取值為 NSParagraphStyle 物件(詳情見下面的API說明) * * * 3. NSForegroundColorAttributeName ->設定字型顏色,取值為 UIColor物件,預設值為黑色 * * * 4. NSBackgroundColorAttributeName
->設定字型所在區域背景顏色,取值為 UIColor物件,預設值為nil, 透明色 * * * 5. NSLigatureAttributeName ->設定連體屬性,取值為NSNumber 物件(整數),0 表示沒有連體字元,1 表示使用預設的連體字元 * * * 6. NSKernAttributeName ->設定字元間距,取值為 NSNumber 物件(整數),正值間距加寬,負值間距變窄 * * * 7. NSStrikethroughStyleAttributeName
->設定刪除線,取值為 NSNumber 物件(整數) * * * 8. NSStrikethroughColorAttributeName ->設定刪除線顏色,取值為 UIColor 物件,預設值為黑色 * * * 9. NSUnderlineStyleAttributeName ->設定下劃線,取值為 NSNumber 物件(整數),列舉常量 NSUnderlineStyle中的值,與刪除線類似 * * * 10. NSUnderlineColorAttributeName ->設定下劃線顏色,取值為 UIColor 物件,預設值為黑色 * * * 11. NSStrokeWidthAttributeName ->設定筆畫寬度(粗細),取值為 NSNumber 物件(整數),負值填充效果,正值中空效果 * * * 12. NSStrokeColorAttributeName ->填充部分顏色,不是字型顏色,取值為 UIColor 物件 * * * 13. NSShadowAttributeName ->設定陰影屬性,取值為 NSShadow 物件 * * * 14. NSTextEffectAttributeName ->設定文字特殊效果,取值為 NSString 物件,目前只有圖版印刷效果可用 * * * 15. NSBaselineOffsetAttributeName ->設定基線偏移值,取值為 NSNumber (float),正值上偏,負值下偏 * * * 16. NSObliquenessAttributeName ->設定字形傾斜度,取值為 NSNumber (float),正值右傾,負值左傾 * * * 17. NSExpansionAttributeName ->設定文字橫向拉伸屬性,取值為 NSNumber (float),正值橫向拉伸文字,負值橫向壓縮文字 * * * 18. NSWritingDirectionAttributeName ->設定文字書寫方向,從左向右書寫或者從右向左書寫 * * * 19. NSVerticalGlyphFormAttributeName ->設定文字排版方向,取值為 NSNumber 物件(整數),0 表示橫排文字,1 表示豎排文字 * * * 20. NSLinkAttributeName ->設定連結屬性,點選後呼叫瀏覽器開啟指定URL地址 * * * 21. NSAttachmentAttributeName ->設定文字附件,取值為NSTextAttachment物件,常用於文字圖片混排 * */ /** * API: NSParagraphStyleAttributeName * * 值為NSParagraphStyle,設定段落屬性,預設值為[NSParagraphStyle defaultParagraphStyle]返回的值。 * * NSMutableParagraphStyleNSParagraphStyle包括一下屬性 * alignment ->對齊方式 * firstLineHeadIndent ->首行縮排 * headIndent ->縮排 * tailIndent ->尾部縮排 * lineBreakMode ->斷行方式 * maximumLineHeight ->最大行高 * minimumLineHeight ->最低行高 * lineSpacing ->行距 * paragraphSpacing ->段距 * paragraphSpacingBefore ->段首空間 * baseWritingDirection ->句子方向 * lineHeightMultiple ->可變行高,乘因數。 * hyphenationFactor ->連字元屬性 */

程式碼

- (void)creatTitleLabel {

    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 320, 400)];
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.layer.borderColor = [UIColor grayColor].CGColor;
    self.titleLabel.layer.borderWidth = 0.5;
    self.titleLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:self.titleLabel];

    NSString *string = @"An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string. ";

    /* 這句話就是對這個類的一個最簡明扼要的概括。NSAttributedString管理一個字串,以及與該字串中的單個字元或某些範圍的字串相關的屬性。它有一個子類NSMutableAttributedString
     * 具體實現時,NSAttributedString維護了一個NSString,用來儲存最原始的字串,另有一個NSDictionary用來儲存各個子串/字元的屬性。
     */


#pragma mark - NSMutableAttributedString 建立
    /* 三種初始化方法,NSMutableAttributedString沒有初始化方法,使用父類初始化方法, 使用initWithString:, initWithString:attributes:, 或者 initWithAttributedString: */
    NSAttributedString *attStri = [[NSAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30]}];

    NSMutableAttributedString *mAttStri = [[NSMutableAttributedString alloc] initWithString:string];


#pragma mark ** 1. NSFontAttributeName 設定字型屬性
    /* 字型大小 及 字型型別 */
    NSRange font_range = [string rangeOfString:@"An"];
    [mAttStri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:font_range];
    [mAttStri addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:17.0] range:NSMakeRange(10, 10)];


#pragma mark ** 2. NSParagraphStyleAttributeName 設定文字段落排版格式
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.firstLineHeadIndent = 20;
    style.lineSpacing = 10;

    [mAttStri addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, mAttStri.length / 2)];

#pragma mark ** 3. NSForegroundColorAttributeName 設定字型顏色
    /* 值為UIColor,字型顏色,預設為黑色. */
    [mAttStri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, mAttStri.length)];


#pragma mark ** 4. NSBackgroundColorAttributeName 設定字型所在區域背景顏色
    /* 值為UIColor,字型背景色,預設透明. */
    [mAttStri addAttribute:NSBackgroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, 20)];


#pragma mark ** 5. NSLigatureAttributeName 設定連體屬性
    /* 取值為NSNumber 物件(整數). 0 表示沒有連體字元, 1 表示使用預設的連體字元. 一般中文用不到,在英文中可能出現相鄰字母連筆的情況 */
    [mAttStri addAttribute:NSLigatureAttributeName value:@0 range:NSMakeRange(0, mAttStri.length)];



#pragma mark ** 6. NSKernAttributeName 設定字元間距
    /* 值為浮點數NSNumber,字距屬性,預設值為0。*/
    [mAttStri addAttribute:NSKernAttributeName value:@3 range:NSMakeRange(0, mAttStri.length)];



#pragma mark ** 7. NSStrikethroughStyleAttributeName 設定刪除線
    /* 值為整型NSNumber,可取值為
        enum {

        NSUnderlineStyleNone = 0×00,

        NSUnderlineStyleSingle = 0×01,

        }; 設定刪除線。
    */
    [mAttStri addAttribute:NSStrikethroughStyleAttributeName value:@3 range:NSMakeRange(3, 7)];


#pragma mark ** 8. NSStrikethroughColorAttributeName 設定刪除線顏色
    /* 這個屬性的值是一個UIColor物件. */
    [mAttStri addAttribute:NSStrikethroughColorAttributeName value:[UIColor blueColor] range:NSMakeRange(3, 3)];


#pragma mark ** 9. NSUnderlineStyleAttributeName 設定下劃線
    /* 取值為 NSNumber 物件(整數),列舉常量 NSUnderlineStyle中的值,與刪除線類似 */
    [mAttStri addAttribute:NSUnderlineStyleAttributeName value:@2 range:NSMakeRange(6, 5)];


#pragma mark ** 10. NSUnderlineColorAttributeName 設定下劃線顏色
    /* 這個屬性的值是一個UIColor物件.預設值為nil. */
    [mAttStri addAttribute:NSUnderlineColorAttributeName value:[UIColor blackColor] range:NSMakeRange(6, 5)];



#pragma mark ** 11. NSStrokeWidthAttributeName 設定筆畫寬度(粗細)
    /* 值為浮點數NSNumber。設定筆畫的粗細。負值填充效果,正值中空效果. */
    [mAttStri addAttribute:NSStrokeWidthAttributeName value:@10 range:NSMakeRange(50, 30)];


#pragma mark ** 12. NSStrokeColorAttributeName 填充部分顏色,
    /* 不是字型顏色,取值為 UIColor 物件 預設值為nil,設定的屬性同ForegroundColor。*/
    [mAttStri addAttribute:NSStrokeColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(50, 20)];


#pragma mark ** 13. NSShadowAttributeName 設定陰影屬性

    /* 值為NSShadow,設定筆畫的陰影,預設值為nil。*/
    NSShadow *shadow = [[NSShadow alloc]init];
    shadow.shadowOffset = CGSizeMake(10, 10);
    shadow.shadowColor = [UIColor greenColor];
    [mAttStri addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(20, 10)];


#pragma mark ** 14. NSTextEffectAttributeName 設定文字特殊效果
    /* 這個屬性的值是一個NSString物件。使用此屬性指定的文字效果,如NSTextEffectLetterpressStyle。此屬性的預設值為nil,表示沒有文字效應。*/
    [mAttStri addAttribute:NSTextEffectAttributeName value:NSTextEffectLetterpressStyle range:NSMakeRange(80, 10)];



#pragma mark ** 15. NSBaselineOffsetAttributeName 設定基線偏移值
    /* 此屬性的值是包含一個浮點值的NSNumber物件,表示的字元從基線偏移的NSNumber物件,預設值是0。正值上偏,負值下偏 */
    [mAttStri addAttribute:NSBaselineOffsetAttributeName value:@5 range:NSMakeRange(112, 10)];


#pragma mark ** 16. NSObliquenessAttributeName 設定字形傾斜度取值為 NSNumber (float),正值右傾,負值左傾
    /* 此屬性的值是包含一個浮點值的NSNumber物件。預設值為0,表示沒有傾斜, 正值右傾,負值左傾。 */
    [mAttStri addAttribute:NSObliquenessAttributeName value:@0.8 range:NSMakeRange(135, 15)];


#pragma mark ** 17. NSExpansionAttributeName 設定文字橫向拉伸屬性
    /* 取值為 NSNumber(float), 正值橫向拉伸文字, 負值橫向壓縮文字 */
    NSRange range =  [string rangeOfString:@"An association of"];
    [mAttStri addAttribute:NSExpansionAttributeName value:@1.0 range:range];



#pragma mark ** 18. NSWritingDirectionAttributeName 設定文字書寫方向
    /** 
     * 取值為包含NSNumber物件的陣列. 從左向右書寫或者從右向左書寫.
     *
     * The values of the NSNumber objects should be 0, 1, 2, or 3, for LRE, RLE, LRO, or RLO respectively, and combinations of NSWritingDirectionLeftToRight and NSWritingDirectionRightToLeft with NSTextWritingDirectionEmbedding or NSTextWritingDirectionOverride, as shown in Values of NSWritingDirectionAttributeName and equivalent markup.

     */
    NSRange rang2 = [string rangeOfString:@"characters and their"];
    [mAttStri addAttribute:NSWritingDirectionAttributeName value:@[@3] range:rang2];



#pragma mark ** 19. NSVerticalGlyphFormAttributeName 設定文字排版方向
    /**
     * 值為整型NSNumber,0為水平排版的字,1為垂直排版的字。注意,在iOS中, 總是以橫向排版
     *
     * In iOS, horizontal text is always used and specifying a different value is undefined.
     */
    [mAttStri addAttribute:NSVerticalGlyphFormAttributeName value:@1 range:NSMakeRange(1, 10)];



#pragma mark ** 20. NSLinkAttributeName 設定連結屬性
    /**
     * 此屬性的值是NSURL物件(首選)或一個NSString物件。此屬性的預設值為nil,表示沒有連結。
     * UILabel無法使用該屬性, 可以使用UITextView 控制元件.
     */
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 450, 320, 60)];
    [self.view addSubview:textView];
    textView.backgroundColor  = [UIColor lightGrayColor];


    NSString *strLink = @"百度連結";
    NSAttributedString *attStr  = [[NSAttributedString alloc] initWithString:strLink attributes:@{NSLinkAttributeName: [NSURL URLWithString:@"http://www.baidu.com"]}];

    textView.editable = NO;

    /* 簽訂協議, 指定代理人之後. 但點選連結時, 會回撥協議方法 (- textView:shouldInteractWithURL:inRange:) */
    textView.delegate = self;

    textView.attributedText = attStr;


#pragma mark ** 21. NSAttachmentAttributeName 設定文字附件
    /* 這個屬性的值是一個NSTextAttachment物件。此屬性的預設值為nil,表示無附件。*/

    /**
     * 關於NSTextAttachment類的簡單說明
     *
     * NSTextAttachment 類有一個指定的初始化方法(- initWithData:ofType:), 需要指定附件文件的資料和附件檔案的型別. 如果附件文件資料指定nil, 那麼系統將會預設指定為image物件作為值. 因此, 也可以通過這個特性實現圖文混排.
     * 下面就以附件為image物件來說明NSAttachmentAttributeName的使用.
     *
     */

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 550, 320, 60)];
    label.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:label];


    /* 下面實現在百度兩個漢字之間插入一個照片 */
    NSString *stiAtt = @"百度";

    NSTextAttachment *attach = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
    attach.bounds = CGRectMake(0, 0, 50, 50);
    attach.image = [UIImage imageNamed:@"baidu.jpg"];

    NSAttributedString *strAtt = [NSAttributedString attributedStringWithAttachment:attach];

    NSMutableAttributedString *strMatt = [[NSMutableAttributedString alloc] initWithString:stiAtt];

    [strMatt insertAttributedString:strAtt atIndex:1];

    label.attributedText = strMatt;

    self.titleLabel.attributedText = mAttStri;
    [self.titleLabel sizeToFit];

}


#pragma mark - textView delegate 
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {

    NSLog(@"%s", __func__);
    NSLog(@"url: %@", URL);
    return YES;
}