iOS富文字(一)屬性化字串

2021-07-06 04:42:54 字數 2496 閱讀 8900

ios一些複雜的文字布局一般都是由底層的core text來實現的,直到ios7蘋果發布了text kit框架,text kit能夠很簡單實現一些複雜的文字樣式以及布局,而text kit富文字框架用到的核心資料結構就是屬性化字串nsattributestring,本篇文章將介紹nsattributestring一些常用屬性和使用方法。

nsattributestring有很多屬性提供來改變字型的樣式,下面**只是列出了一些常用的屬性,如果想更改更多的字型樣式請參考蘋果官方文件,使用方法大同小異。

**示例

@inte***ce

viewcontroller ()

@property (weak,nonatomic) iboutlet

uilabel *stringlabel;

@end

@implementation

viewcontroller

- (void)viewdidload ;

[attributedstring addattributes:boldfontas range:[string rangeofstring:@"boldfont"]];

//字型顏色屬性

nsdictionary *redfondas = @;

[attributedstring addattributes:redfondas range:[string rangeofstring:@"redfont"]];

//字型背景顏色和字型顏色屬性

nsdictionary *bulebackgroundas = @;

[attributedstring addattributes:bulebackgroundas range:[string rangeofstring:@"bulebackground"]];

//字型下劃線與字型下劃線顏色屬性

nsdictionary *underlineas = @;

[attributedstring addattributes:underlineas range:[string rangeofstring:@"underline"]];

//字型陰影屬性

nsshadow *shadow = [[nsshadow alloc] init];

shadow.shadowoffset = cgsizemake(2, 2);

shadow.shadowcolor = [uicolor orangecolor];

nsdictionary *shadowas = @;

[attributedstring addattributes:shadowas range:[string rangeofstring:@"shadow"]];

//設定label的字串屬性

_stringlabel.attributedtext = attributedstring;

}

實現效果

nsattributestring的段落樣式包括外邊距,字型對齊,字型縮排等。在ios中段落用\n用來分隔,如果在乙個段落中使用多個段落樣式的話,那麼只對段落中第乙個字元使用的樣式有效。在一段文字中如果沒有\n的話那麼這一段文字就是乙個段落。在顯示中常常文字過長系統會自動換行,不管換多少行都只是乙個段落。

對整體的文字應用段落樣式

@inte***ce

viewcontroller ()

@property (weak, nonatomic) iboutlet

uilabel *paragraphlabel;

@end

@implementation

viewcontroller

- (void)viewdidload ;

nsmutableattributedstring *attributestring = [[nsmutableattributedstring alloc] initwithstring:paragraphstring attributes:attribute];

_paragraphlabel.attributedtext = attributestring;

}

設定段落前

設定段落後

屬性字串(富文字)的使用

改變字串中某些字串字型的顏色 nsmutableattributedstring attrstr nsmutableattributedstring alloc initwithstring str attrstr addattribute nsforegroundcolorattributenam...

iOS 富文字屬性

nsfontattributename 設定字型屬性,預設值 字型 helvetica neue 字型大小 12 nsforegroundcolorattributenam 設定字型顏色,取值為 uicolor物件,預設值為黑色 nsbackgroundcolorattributename 設定字型...

iOS筆記 富文字處理屬性

nsfontattributename 設定字型屬性,預設值 字型 helvetica neue 字型大小 12 nsforegroundcolorattributenam 設定字型顏色,取值為 uicolor物件,預設值為黑色 nsbackgroundcolorattributename 設定字型...