iOS中NSAttributedString 的21種屬性詳細(xì)介紹

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

核心API: NSAttributedString. NSMutableAttributedString.

  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管理一個字符串,以及與該字符串中的單個字符或某些范圍的字符串相關(guān)的屬性溃槐。它有一個子類NSMutableAttributedString
 * 具體實現(xiàn)時匣砖,NSAttributedString維護(hù)了一個NSString,用來保存最原始的字符串昏滴,另有一個NSDictionary用來保存各個子串/字符的屬性猴鲫。
 */
#pragma mark - NSMutableAttributedString 創(chuàng)建
/* 三種初始化方法,NSMutableAttributedString沒有初始化方法,使用父類初始化方法, 使用initWithString:, initWithString:attributes:, 或者 initWithAttributedString: */
  NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30]}];
    
  NSMutableAttributedString *mAttStr = [[NSMutableAttributedString alloc] initWithString:string];

1.NSFontAttributeName ->設(shè)置字體屬性,默認(rèn)值:字體:Helvetica(Neue) 字號:12

/* 設(shè)置字體大小及字體類型 */
  NSRange font_range = [string rangeOfString:@"An"];
  [mAttStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:font_range];
  [mAttStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:17.0] range:NSMakeRange(10, 10)];

2.NSParagraphStyleAttributeName ->設(shè)置文本段落排版格式谣殊,取值為 NSParagraphStyle 對象(詳情見如下代碼)

  • NSParagraphStyle與NSMutableParagraphStyle包括以下屬性

    • alignment ->對齊方式
    • firstLineHeadIndent ->首行縮進(jìn)
    • headIndent ->縮進(jìn)
    • tailIndent ->尾部縮進(jìn)
    • lineBreakMode ->斷行方式
    • maximumLineHeight ->最大行高
    • minimumLineHeight ->最低行高
    • lineSpacing ->行距
    • paragraphSpacing ->段距
    • paragraphSpacingBefore ->段首空間
    • baseWritingDirection ->句子方向
    • lineHeightMultiple ->可變行高,乘因數(shù)拂共。
    • hyphenationFactor ->連字符屬性
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.firstLineHeadIndent = 10;
    style.lineSpacing = 10;
    
    [mAttStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(10, 10)];

3.NSForegroundColorAttributeName ->設(shè)置字體顏色,取值為 UIColor對象姻几,默認(rèn)值為黑色


[mAttStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(10, 10)];

4.NSBackgroundColorAttributeName ->設(shè)置字體所在區(qū)域背景顏色宜狐,取值為 UIColor對象,默認(rèn)值為nil, 透明色


[mAttStr addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(10, 10)];

5.NSLigatureAttributeName ->設(shè)置連體屬性蛇捌,取值為NSNumber 對象(整數(shù))抚恒,0 表示沒有連體字符,1 表示使用默認(rèn)的連體字符

[mAttStr addAttribute:NSLigatureAttributeName value:@1 range:NSMakeRange(10, 10)];

6.NSKernAttributeName ->設(shè)置字符間距络拌,取值為 NSNumber 對象(整數(shù))柑爸,正值間距加寬,負(fù)值間距變窄

[mAttStr addAttribute:NSKernAttributeName value:@2 range:NSMakeRange(10, 10)];

7.NSStrikethroughStyleAttributeName ->設(shè)置刪除線盒音,取值為 NSNumber 對象(整數(shù))



/* 值為整型NSNumber表鳍,可取值為 NSUnderlineStyle
    enum {
    NSUnderlineStyleNone                                    = 0x00,
    NSUnderlineStyleSingle                                  = 0x01,
    NSUnderlineStyleThick NS_ENUM_AVAILABLE(10_0, 7_0)      = 0x02,
    NSUnderlineStyleDouble NS_ENUM_AVAILABLE(10_0, 7_0)     = 0x09,

    NSUnderlinePatternSolid NS_ENUM_AVAILABLE(10_0, 7_0)      = 0x0000,
    NSUnderlinePatternDot NS_ENUM_AVAILABLE(10_0, 7_0)        = 0x0100,
    NSUnderlinePatternDash NS_ENUM_AVAILABLE(10_0, 7_0)       = 0x0200,
    NSUnderlinePatternDashDot NS_ENUM_AVAILABLE(10_0, 7_0)    = 0x0300,
    NSUnderlinePatternDashDotDot NS_ENUM_AVAILABLE(10_0, 7_0) = 0x0400,

    NSUnderlineByWord NS_ENUM_AVAILABLE(10_0, 7_0)            = 0x8000
        }; 設(shè)置刪除線。
    */
    [mAttStr addAttribute:NSStrikethroughStyleAttributeName value:@3 range:NSMakeRange(10, 10)];

8.NSStrikethroughColorAttributeName ->設(shè)置刪除線顏色祥诽,取值為 UIColor 對象譬圣,默認(rèn)值為黑色

[mAttStr addAttribute:NSStrikethroughColorAttributeName value:[UIColor blueColor] range:NSMakeRange(10, 10)];

9.NSUnderlineStyleAttributeName ->設(shè)置下劃線,取值為 NSNumber 對象(整數(shù))雄坪,枚舉常量 NSUnderlineStyle中的值厘熟,與刪除線類似

[mAttStr addAttribute:NSUnderlineStyleAttributeName value:@3 range:NSMakeRange(10, 10)];

10.NSUnderlineColorAttributeName ->設(shè)置下劃線顏色,取值為 UIColor 對象,默認(rèn)值為nil

[mAttStr addAttribute:NSUnderlineColorAttributeName value:[UIColor blackColor] range:NSMakeRange(10, 10)];

11.NSStrokeWidthAttributeName ->設(shè)置筆畫寬度(粗細(xì))绳姨,取值為 NSNumber 對象(整數(shù))登澜,負(fù)值填充效果,正值中空效果

[mAttStr addAttribute:NSStrokeWidthAttributeName value:@10 range:NSMakeRange(10, 10)];

12.NSStrokeColorAttributeName ->填充部分顏色飘庄,不是字體顏色脑蠕,取值為 UIColor 對象 默認(rèn)值為nil,設(shè)置的屬性同F(xiàn)oregroundColor

[mAttStr addAttribute:NSStrokeColorAttributeName value:[UIColor radColor] range:NSMakeRange(10, 10)];

13.NSShadowAttributeName ->設(shè)置陰影屬性跪削,取值為 NSShadow 對象 默認(rèn)值為nil


NSShadow *shadow = [[NSShadow alloc]init];
shadow.shadowOffset = CGSizeMake(10, 10);
shadow.shadowColor = [UIColor redColor];
[mAttStr addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(10, 10)];

14.NSTextEffectAttributeName ->設(shè)置文本特殊效果谴仙,取值為 NSString 對象,目前只有圖版印刷效果可用, 使用此屬性指定的文字效果碾盐,如NSTextEffectLetterpressStyle晃跺。此屬性的默認(rèn)值為nil,表示沒有文本效應(yīng)

[mAttStr addAttribute:NSTextEffectAttributeName value:NSTextEffectLetterpressStyle range:NSMakeRange(10, 10)];

15.NSBaselineOffsetAttributeName ->設(shè)置基線偏移值毫玖,取值為 NSNumber (float),正值上偏掀虎,負(fù)值下偏, 默認(rèn)值是0

[mAttStr addAttribute:NSBaselineOffsetAttributeName value:@1 range:NSMakeRange(10, 10)];

16.NSObliquenessAttributeName ->設(shè)置字形傾斜度,取值為 NSNumber (float),正值右傾付枫,負(fù)值左傾, 默認(rèn)值是0(表示沒有傾斜)


[mAttStr addAttribute:NSObliquenessAttributeName value:@0.5 range:NSMakeRange(10, 10)];

17.NSExpansionAttributeName ->設(shè)置文本橫向拉伸屬性涩盾,取值為 NSNumber (float),正值橫向拉伸文本,負(fù)值橫向壓縮文本

[mAttStr addAttribute:NSExpansionAttributeName value:@1.0 range:NSMakeRange(10, 10)];

18.NSWritingDirectionAttributeName ->設(shè)置文字書寫方向励背,從左向右書寫或者從右向左書寫


//取值為包含NSNumber對象的數(shù)組. 從左向右書寫或者從右向左書寫.
// NSArray of NSNumbers representing the nested levels of writing direction overrides as 
defined by Unicode LRE, RLE, LRO, and RLO characters.  The control characters can be 
obtained by masking NSWritingDirection and NSTextWritingDirection values.  LRE: 
NSWritingDirectionLeftToRight|NSWritingDirectionEmbedding, RLE: 
NSWritingDirectionRightToLeft|NSWritingDirectionEmbedding, LRO: 
NSWritingDirectionLeftToRight|NSWritingDirectionOverride, RLO: 
NSWritingDirectionRightToLeft|NSWritingDirectionOverride,

[mAttStr addAttribute:NSWritingDirectionAttributeName value:@[@2] range:NSMakeRange(10, 10)];

19.NSVerticalGlyphFormAttributeName ->設(shè)置文字排版方向春霍,取值為 NSNumber 對象(整數(shù)),0 表示橫排文本叶眉,1 表示豎排文本 在iOS中, 總是以橫向排版

[mAttStr addAttribute:NSVerticalGlyphFormAttributeName value:@0 range:NSMakeRange(10, 10)];

20.NSLinkAttributeName ->設(shè)置鏈接屬性址儒,點擊后調(diào)用瀏覽器打開指定URL地址

/**
 * 此屬性的值是NSURL對象(首選)或一個NSString對象。此屬性的默認(rèn)值為nil衅疙,表示沒有鏈接莲趣。
 * UILabel無法使用該屬性, 可以使用UITextView 控件.
 */
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
    [self.view addSubview:textView];
    textView.backgroundColor  = [UIColor redColor];
    
    
    NSString *strLink = @"百度鏈接";
    NSAttributedString *attStrUrl  = [[NSAttributedString alloc] initWithString:strLink attributes:@{NSLinkAttributeName: [NSURL URLWithString:@"http://www.baidu.com"]}];
    
    textView.editable = NO;
    
    /* 簽訂協(xié)議, 指定代理人之后. 但點擊鏈接時, 會回調(diào)協(xié)議方法 (- textView:shouldInteractWithURL:inRange:) */
    textView.delegate = self;
    
    textView.attributedText = attStr;
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"url: %@", URL);
    return YES;
}

注意:

@interface ViewController () <UITextViewDelegate>

21.NSAttachmentAttributeName ->設(shè)置文本附件,取值為NSTextAttachment對象,常用于文字圖片混排


/* 這個屬性的值是一個NSTextAttachment對象。此屬性的默認(rèn)值為nil饱溢,表示無附件喧伞。*/
    
    /**
     * 關(guān)于NSTextAttachment類的簡單說明
     *
     * NSTextAttachment 類有一個指定的初始化方法(- initWithData:ofType:), 需要指定附件文檔的數(shù)據(jù)和附件文件的類型. 如果附件文檔數(shù)據(jù)指定nil, 那么系統(tǒng)將會默認(rèn)指定為image對象作為值. 因此, 也可以通過這個特性實現(xiàn)圖文混排.
     * 下面就以附件為image對象來說明NSAttachmentAttributeName的使用.
     *
     */
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
    label.backgroundColor = [UIColor redColor];
    [self.view addSubview:label];
    
    
    /* 下面實現(xiàn)在百度兩個漢字之間插入一個照片 */
    NSString *stiAtt = @"百度";
    
    NSTextAttachment *attach = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
    attach.bounds = CGRectMake(0, 0, 50, 50);
    attach.image = [UIImage imageNamed:@"taobao.jpg"];
    
    NSAttributedString *strAtt = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *strMatt = [[NSMutableAttributedString alloc] initWithString:stiAtt];
    
    [strMatt insertAttributedString:strAtt atIndex:1];
    
    label.attributedText = strMatt;
    
    self.titleLabel.attributedText = mAttStr;
    [self.titleLabel sizeToFit];

在此要感謝我的啟蒙老師, 原哥, 是他帶我走上了iOS編程這條"不歸"之路!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市绩郎,隨后出現(xiàn)的幾起案子潘鲫,更是在濱河造成了極大的恐慌,老刑警劉巖肋杖,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件溉仑,死亡現(xiàn)場離奇詭異,居然都是意外死亡状植,警方通過查閱死者的電腦和手機(jī)浊竟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進(jìn)店門怨喘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人振定,你說我怎么就攤上這事必怜。” “怎么了后频?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵梳庆,是天一觀的道長。 經(jīng)常有香客問我徘郭,道長靠益,這世上最難降的妖魔是什么丧肴? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任残揉,我火速辦了婚禮,結(jié)果婚禮上芋浮,老公的妹妹穿的比我還像新娘抱环。我一直安慰自己,他們只是感情好纸巷,可當(dāng)我...
    茶點故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布镇草。 她就那樣靜靜地躺著,像睡著了一般瘤旨。 火紅的嫁衣襯著肌膚如雪梯啤。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天存哲,我揣著相機(jī)與錄音因宇,去河邊找鬼。 笑死祟偷,一個胖子當(dāng)著我的面吹牛察滑,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播修肠,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼贺辰,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了嵌施?” 一聲冷哼從身側(cè)響起饲化,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎吗伤,沒想到半個月后滓侍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡牲芋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年撩笆,在試婚紗的時候發(fā)現(xiàn)自己被綠了捺球。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,773評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡夕冲,死狀恐怖氮兵,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情歹鱼,我是刑警寧澤泣栈,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站弥姻,受9級特大地震影響南片,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜庭敦,卻給世界環(huán)境...
    茶點故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一疼进、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧秧廉,春花似錦伞广、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蔽豺,卻和暖如春区丑,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背修陡。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工沧侥, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人濒析。 一個月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓正什,卻偏偏與公主長得像,于是被迫代替她去往敵國和親号杏。 傳聞我的和親對象是個殘疾皇子婴氮,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,689評論 2 354

推薦閱讀更多精彩內(nèi)容