In iOS development, there is often a piece of text that displays different colors and fonts, or the need to add lines or underscores to a few words. Before the online to find some information, some redraw Uilabel Textlayer, somewith HTML5 to achieve, are more troublesome, and many Uilabel properties also do not work, the effect is not ideal. Later I learned that nsmuttableattstring (string with attributes), some of the above requirements can be easily implemented.
Nsmuttableattstring method
Set multiple properties for text in a range
-(void) SetAttributes: (nsdictionary *) Attrs range: (nsrange) range;
Add a property to a range of text
-(void) AddAttribute: (NSString *) Name value: (ID) value range: (nsrange) range;
Add multiple attributes to a range of text
-(void) AddAttributes: (nsdictionary *) Attrs range: (nsrange) range;
To remove an attribute in a range
-(void) RemoveAttribute: (NSString *) name range: (nsrange) range;
Common Properties and descriptions
Nsfontattributename Fonts
Nsparagraphstyleattributename paragraph format
Nsforegroundcolorattributename Font Color
Nsbackgroundcolorattributename Background Color
Nsstrikethroughstyleattributename Strikethrough formatting
Nsunderlinestyleattributename underline format
Nsstrokecolorattributename Strikethrough Color
Nsstrokewidthattributename Strikethrough Width
Nsshadowattributename Shadow
Example one:
UILabel *testlabel = [[UILabel alloc]initwithframe:cgrectmake (0, -, the, -)]; Testlabel.backgroundcolor=[Uicolor Lightgraycolor]; Testlabel.textalignment=Nstextalignmentcenter; Nsmutableattributedstring*ATTRIBUTEDSTR = [[nsmutableattributedstring alloc]initwithstring:@"It's a nice day today."]; [Attributedstr addattribute:nsfontattributename value:[uifont systemfontofsize:16.0] Range:nsmakerange (2,2)]; [Attributedstr addattribute:nsforegroundcolorattributename Value:[uicolor Redcolor] Range:nsmakerange (2,2)]; Testlabel.attributedtext=Attributedstr; [Self.view Addsubview:testlabel];
Effect:
Example two:
UILabel *titleview =[[UILabel alloc] init]; Titleview.width= $; Titleview.height= -; Titleview.textalignment=Nstextalignmentcenter; //Wrap LineTitleview.numberoflines =0; Titleview.y= -; NSString*STR = [NSString stringWithFormat:@"%@\n%@", prefix, name]; //create a string with attributes (such as text attributes such as color attributes, font properties, and so on)Nsmutableattributedstring *attrstr =[[Nsmutableattributedstring alloc] initwithstring:str]; //Add Property[Attrstr addattribute:nsfontattributename Value:[uifont boldsystemfontofsize: -] Range:[str Rangeofstring:prefix]]; [Attrstr addattribute:nsfontattributename value:[uifont systemfontofsize: A] Range:[str Rangeofstring:name]]; Titleview.attributedtext= Attrstr;
In the example two, Range:[str Rangeofstring:name] finds the name of the range where Str is located.
Reference Blog: http://snowyshell.blog.163.com/blog/static/2209140342014475383375/
IOS UI Basics -17.0 uilable nsmutableattributedstring