Use nsmutableattributedstring to add underscores, strikethrough, shadows, fills, different font colors, and more

Source: Internet
Author: User
Tags dashed line

In iOS development, sometimes you encounter the need to add an underscore, or to set the color of a few words in a string, the most common chestnut is the registration page:


Almost every sign-up page reads, "Click Next to indicate that you have agreed to the User Service agreement", and you can see that the "User Service agreement" words are orange, and they are underlined below. How is this going to be achieved?


Some students may say: "Different colors set two labels, let the left label display the first half of the sentence and set to black, let the right label display the second half sentence and set to orange on the line." "It may be a solution, but it feels a little troublesome, and if there are many colors?" Do you want to set a lot of labels ...


Nsmutableattributedstring can be a perfect solution to these problems. Let's first talk about the four methods associated with attributes:

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;

Remove an attribute from a range

-(void) RemoveAttribute: (nsstring *) name range: (nsrange) range;


Let's raise a chestnut :

-(void) viewdidload {    [super viewdidload];    UILabel *label = [[UILabel alloc] Initwithframe:cgrectmake (0, +, screenwidth, +)];    Label.font = [Uifont systemfontofsize:18]; Font size    label.textalignment = nstextalignmentcenter;//text alignment        nsmutableattributedstring *str = [[ Nsmutableattributedstring alloc] initwithstring:        @ "Click Next to indicate that you have consented to the User Service agreement"];    [str addattribute:nsforegroundcolorattributename value:        [Uicolor colorwithred:100/255.0 green:100/255.0 blue:100/255.0 alpha:1] Range:nsmakerange (0,11)];    [str addattribute:nsforegroundcolorattributename value:        [Uicolor colorwithred:255/255.0 green:110/255.0 blue:17/255.0 alpha:1] Range:nsmakerange (11,8)];    Label.attributedtext = str;    [Self.view Addsubview:label];}

We create a Nsmutableattributedstring object str, and then add a property to it, the name of this property is Nsforegroundcolorattributename, which is the color of the text, and its value is Uicolor Type, the default is black, we give it a custom color. Then we set its range, Nsmakerange (0, 11) means, starting with the No. 0 word, a total of 11 words. This range is actually "click Next to show that you have agreed to" these 11 words. (In fact, these 11 words in the first picture are not black, but close to black, which is not important ~)

Then we add a property to the string, which is still nsforegroundcolorattributedname, but the color is orange, and the range is from the 11th (don't forget the number starts with 0), altogether 8 characters. This scope is actually "User Service agreement" (the title number also counts)


Now let's run the program to see the effect:



The text color has been done, and then we'll underline it. We add one more sentence on the basis of the original code:

-(void) viewdidload {[Super viewdidload];    UILabel *label = [[UILabel alloc] Initwithframe:cgrectmake (0, +, ScreenWidth, 40)]; Label.font = [Uifont systemfontofsize:18]; Font size label.textalignment = Nstextalignmentcenter; Text alignment nsmutableattributedstring *str = [[Nsmutableattributedstring alloc] initwithstring: @ "Click Next to indicate that you have agreed to the    User Service agreement "]; [Str addattribute:nsforegroundcolorattributename value: [Uicolor colorwithred:100/255.0 green:100/255.0 BLUE:100/25    5.0 Alpha:1] Range:nsmakerange (0,11)]; [Str addattribute:nsforegroundcolorattributename value: [Uicolor colorwithred:255/255.0 green:110/255.0 blue:17/255    .0 Alpha:1] Range:nsmakerange (11,8)]; [Str addattribute:nsunderlinestyleattributename value: [NSNumber Numberwithinteger:nsunderlinestylesingle] Range:NS Makerange (12, 6)];    Underline label.attributedtext = str; [Self.view Addsubview:label];}


The meaning of this sentence is to add a property to Str, whose name is Nsunderlinestyleattributename, which is the type of underline. Its value is Nsinteger type, default is 0, that is, no underscore. The range is starting from the 12th word, altogether 6 words. The "User Service terms".


Be careful here. Let's take a look at the method prototypes for adding properties:

-( void nsstring  *) Name value: ( Span style= "FONT-SIZE:14PX; font-family: ' Courier New '; line-height:24.5px; Color:rgb (187,44,162) ">id nsrange

Note that the parameter value is of type ID. See this sentence, do you know what I want to say?

The ID is a Objective-c object. And Nsinteger is the basic data type, not an object. So it must be written in the form of [NSNumber numberwithinteger:123].

In setting this value, I do not know the specific should be set to a few, I tried a good majority, but found that there is no wrong. Later Baidu a bit, only to know that its value has an enumeration:

typedef ns_enum (Nsinteger, Nsunderlinestyle) {    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} ns_enum_ AVAILABLE (10_0, 6_0);


In fact, when you set the strikethrough Nsstrikethroughcolorattributename, the value is also the enumeration.

//Nsunderlinestylenone do not set underline/delete lines

//Nsunderlinestylesingle set underline/ strikethrough as a thin single line

//Nsunderlinestylethick set underline/ strikethrough as a thick single line

//Nsunderlinestyledouble set underline/ strikethrough as a thin double line


Nsunderlinepatternsolid settingsUnderline/Strikethrough style is a continuous solid line

Nsunderlinepatterndot Set the underline/ strikethrough style to a point, that is, a dashed line, such as this:--

Nsunderlinepatterdash set the underline/ strikethrough style to dashes, for example: —— —— ——

Nsunderlinepatterndashdot Set the underline/ strikethrough style to consecutive dashes and dots, such as this:---------

Nsunderlinepatterndashdotdot Set the underline/ strikethrough style to a continuous dash, dot, point, for example:------------


Nsunderlinebyword do not set underline/strikethrough in places with spaces


Why do I have to divide them into three paragraphs? Because they belong to three kinds, the setting is not necessarily only one, you can set two or three of them at the same time. such as this:

[str addattribute:nsunderlinestyleattributename value:        [NSNumber numberwithinteger:nsunderlinestyledouble | Nsunderlinepatterndot] Range:nsmakerange (12, 6)];
This line of code is to add an underscore to the User Service agreement, but this time the underscore is two lines and a dashed line. (Note: the ' | ' operator is used to satisfy multiple items at the same time.)


In fact, the color of the underline can also be set. If not set, the default is the same as the text color, which is orange. Let's try to change the underline to blue to see:

-(void) viewdidload {[Super viewdidload];    UILabel *label = [[UILabel alloc] Initwithframe:cgrectmake (0, +, ScreenWidth, 40)]; Label.font = [Uifont systemfontofsize:18]; Font size label.textalignment = Nstextalignmentcenter; Text alignment nsmutableattributedstring *str = [[Nsmutableattributedstring alloc] initwithstring: @ "Click Next to indicate that you have agreed to the    User Service agreement "]; [Str addattribute:nsforegroundcolorattributename value: [Uicolor colorwithred:100/255.0 green:100/255.0 BLUE:100/25    5.0 Alpha:1] Range:nsmakerange (0,11)]; [Str addattribute:nsforegroundcolorattributename value: [Uicolor colorwithred:255/255.0 green:110/255.0 blue:17/255    .0 Alpha:1] Range:nsmakerange (11,8)]; [Str addattribute:nsunderlinestyleattributename value: [NSNumber Numberwithinteger:nsunderlinestylesingle] Range:NS Makerange (12, 6)]; Underline type [str addattribute:nsunderlinecolorattributename value: [Uicolor Bluecolor] Range:nsmakerange (12, 6)]; Underline Color Label.attributedtext = Str [Self.view Addsubview:label];}


Run it and the results are as follows:




We'll raise a chestnut , add a bold version of the strikethrough, set the strikethrough color to black (if not set color, also default and text color)

-(void) viewdidload {[Super viewdidload];    UILabel *label = [[UILabel alloc] Initwithframe:cgrectmake (0, +, ScreenWidth, 40)]; Label.font = [Uifont systemfontofsize:18]; Font size label.textalignment = Nstextalignmentcenter; Text alignment nsmutableattributedstring *str = [[Nsmutableattributedstring alloc] initwithstring: @ "Click Next to indicate that you have agreed to the    User Service agreement "]; [Str addattribute:nsforegroundcolorattributename value: [Uicolor colorwithred:100/255.0 green:100/255.0 BLUE:100/25    5.0 Alpha:1] Range:nsmakerange (0,11)]; [Str addattribute:nsforegroundcolorattributename value: [Uicolor colorwithred:255/255.0 green:110/255.0 blue:17/255    .0 Alpha:1] Range:nsmakerange (11,8)]; [Str addattribute:nsunderlinestyleattributename value: [NSNumber Numberwithinteger:nsunderlinestylesingle] Range:NS Makerange (12, 6)]; Underline type [str addattribute:nsunderlinecolorattributename value: [Uicolor Bluecolor] Range:nsmakerange (12, 6)]; Underline color [str addattribute:nsstrikeThroughstyleattributename value: [NSNumber Numberwithinteger:nsunderlinestylethick] Range:nsmakerange (12, 6)]; Strikethrough Type [str addattribute:nsstrikethroughcolorattributename value: [Uicolor Blackcolor] Range:nsmakerange (12, 6 )];    Strikethrough color label.attributedtext = str; [Self.view Addsubview:label];}

Then run one down to see the effect:



Let's raise the last chestnut ( chestnut said: "Can not lift me ~), set the fill:

-(void) viewdidload {[Super viewdidload];    UILabel *label = [[UILabel alloc] Initwithframe:cgrectmake (0, +, ScreenWidth, 40)]; Label.font = [Uifont systemfontofsize:18]; Font size label.textalignment = Nstextalignmentcenter; Text alignment nsmutableattributedstring *str = [[Nsmutableattributedstring alloc] initwithstring: @ "Click Next to indicate that you have agreed to the    User Service agreement "]; [Str addattribute:nsforegroundcolorattributename value: [Uicolor colorwithred:100/255.0 green:100/255.0 BLUE:100/25    5.0 Alpha:1] Range:nsmakerange (0,11)]; [Str addattribute:nsforegroundcolorattributename value: [Uicolor colorwithred:255/255.0 green:110/255.0 blue:17/255    .0 Alpha:1] Range:nsmakerange (11,8)]; [Str addattribute:nsstrokewidthattributename value: [NSNumber numberwithfloat:3.0] Range:nsmakerange (11, 8)];    Set padding label.attributedtext = str; [Self.view Addsubview:label];}

Then run one down to see the effect:


Similarly, the fill can also set the color, if not set, the default and text color.


Nsmutableattributedstring can also set many other properties, such as paragraph formatting, shading, etc. (there are many more)

For a complete study, please refer to Apple's official documentation: Portal


Finally want to talk about its shortcomings, perhaps some students have found that the underline from the text too close! You cannot set the distance between the underline and the text, which is where it is in the ointment.

Use nsmutableattributedstring to add underscores, strikethrough, shadows, fills, different font colors, and more

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.