I’m going to talk about NSAttributedString. Make sure you can encapsulate the RICH text API yourself after reading this article. Here’s the Demo of the encapsulating API. Use it! SAO years!

First, common requirements encapsulation

  • Requirements: In our daily development, there will be a need to change the color of some words in some sentences. Of course, the color is generally for emphasis, often the same color, so the following code is simply to change the color of some words in a sentence

/** * Simply change the color of some words in a sentence ** @param color the color to change to * @param totalStr Total string * @param subArray the text array to change the color ** @return generated rich text * /
+ (NSMutableAttributedString *)ls_changeCorlorWithColor:(UIColor *)color TotalString:(NSString *)totalStr SubStringArray:(NSArray *)subArray {

    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalStr];
    for (NSString *rangeStr in subArray) {

        NSRange range = [totalStr rangeOfString:rangeStr options:NSBackwardsSearch];
        [attributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
    }

    return attributedStr;
}Copy the code
  • Requirements: You need to change the word spacing to fit the overall UI

/** * Simply change the word spacing of the sentence (requires 
      
       ) ** @param totalString String to change * @param space word spacing ** @return generated rich text */
      
+ (NSMutableAttributedString *)ls_changeSpaceWithTotalString:(NSString *)totalString Space:(CGFloat)space {

    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];
    long number = space;
    CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);
    [attributedStr addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0,[attributedStr length])];
    CFRelease(num);

    return attributedStr;
}Copy the code
  • Requirement: You need to change the line spacing to fit the overall UI

/** * simply change paragraph line spacing ** @param totalString String to change * @param lineSpace line spacing ** @return generated rich text */
+ (NSMutableAttributedString *)ls_changeLineSpaceWithTotalString:(NSString *)totalString LineSpace:(CGFloat)lineSpace {

    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];

    [attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [totalString length])];

    return attributedStr;
}Copy the code
  • Need: Change line spacing and word spacing at the same time
/** * change both line spacing and word spacing ** @param totalString String that needs to be changed * @param lineSpace line spacing * @param textSpace word spacing ** @return generated rich text */
+ (NSMutableAttributedString *)ls_changeLineAndTextSpaceWithTotalString:(NSString *)totalString LineSpace:(CGFloat)lineSpace textSpace:(CGFloat)textSpace {

    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];

    [attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [totalString length])];

    long number = textSpace;
    CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);
    [attributedStr addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0,[attributedStr length])];
    CFRelease(num);

    return attributedStr;
}Copy the code
  • Requirements: Change the color of some text and modify its font to highlight the emphasis
/** * change the color of some text and set its font separately ** @param font set font * @param color color * @param totalString totalString * @param subArray array of characters you want to change color * * @return generates rich text */
+ (NSMutableAttributedString *)ls_changeFontAndColor:(UIFont *)font Color:(UIColor *)color TotalString:(NSString *)totalString SubStringArray:(NSArray *)subArray {

    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];

    for (NSString *rangeStr in subArray) {

        NSRange range = [totalString rangeOfString:rangeStr options:NSBackwardsSearch];

        [attributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
        [attributedStr addAttribute:NSFontAttributeName value:font range:range];
    }

    return attributedStr;
}Copy the code

The above API comprehensive renderings are shown below

Talk about NSAttributedString

1. Initialization method

- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)attrs;
- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;Copy the code
  • The first uses string initialization to initialize rich text
  • The second initializes rich text using a string and a dictionary of attributes (the attributes associated with configuring rich text)
  • The third way is to initialize rich text with other rich text

2. Common operation API

  • Adds an attribute to a text in a range
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;Copy the code

Example:

  • Add multiple attributes to text in a range (both apis have the same effect as the format)
- (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;

- (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range;Copy the code

Example:

  • Remove a property from a range (contrast with the Add Property API, not in the example)
- (void)removeAttribute:(NSString *)name range:(NSRange)range;Copy the code
  • Other parts of the API (see the name of the meaning, can be compared with NSString without further description)
- (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString;
- (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc;
- (void)appendAttributedString:(NSAttributedString *)attrString;
- (void)deleteCharactersInRange:(NSRange)range;
- (void)setAttributedString:(NSAttributedString *)attrString;Copy the code

3, related can set the attribute comparison

From API, we can know that for rich text, adding a single attribute and adding an attribute dictionary is called its core method, that is, one key corresponds to one Value. As long as we can understand the corresponding effects of various attributes, we can combine them at will and work out a package API suitable for various needs.

  • NSFontAttributeName: font size value: UIFont type
  • NSParagraphStyleAttributeName: Paragraph style

    Value Value: NSParagraphStyle type (whose attributes are as follows)
    • LineSpacing lineSpacing (see the set lineSpacing API above for specific usage)
    • paragraphSpacing
    • Alignment Mode
    • FirstLineHeadIndent Specifies the indent pixels at the beginning of a paragraph
    • HeadIndent adjusts the indent pixels of all text
  • NSForegroundColorAttributeName font color value value: UIColor type
  • NSBackgroundColorAttributeName background color value value: UIColor type
  • NSObliquenessAttributeName font coarse tilt value value: NSNumber type
  • NSExpansionAttributeName Bold value Indicates the NSNumber type (ratio). 0 is the same as 1 and doubled
  • NSKernAttributeName Word spacing value The value is of the CGFloat type
  • NSUnderlineStyleAttributeName underscores the value value: 1 or 0
  • NSUnderlineColorAttributeName underline color value value: UIColor type
  • NSStrikethroughStyleAttributeName strikethrough the value value: 1 or 0
  • NSStrikethroughColorAttributeName strikethrough color value value: UIColor type
  • NSStrokeColorAttributeName font color value value: UIColor type
  • NSStrokeWidthAttributeName font stroke value value: CGFloat
  • NSLigatureAttributeName Value The value can be 1 or 0
  • NSShadowAttributeNameShadow value Value: NSShawdow type (below are its attributes)
    • ShadowOffset Indicates the offset between the shadow and the string
    • ShadowBlurRadius the degree of shadowBlurRadius
    • ShadowColor indicates the shadowColor
  • NSTextEffectAttributeName set the text special effects, possesses the printing effect is available at present, only the value value: nsstrings type
  • NSAttachmentAttributeName set attachment value text value: NSTextAttachment type (didn’t studied, but baidu studies)
  • NSLinkAttributeName Link Value Value: Preferred NSURL or NSString
  • NSBaselineOffsetAttributeName baseline offset value value: NSNumber type
  • NSWritingDirectionAttributeName text direction Respectively represent different text value direction value: @ [@ (1), @ (2)]
  • NSVerticalGlyphFormAttributeName horizontal or vertical text in iOS no eggs, version does not support vertical value value: 1 vertical level 0

Third, sample Demo explanation

Demo is here, click to jump to

  • The API path address is as follows:
/YiDing/Class/Helpers/LSCoreToolCenterCopy the code

Screenshot below:

  • The following is an example path:
/YiDing/Class/Sections/LSSection/NSMutableAttributedStringCopy the code

The screenshot below

Four, update,

7.18 Late update: Some children want to be able to operate all the same substrings, so we added a method to get the location array and encapsulated it, the effect picture has been updated, interested can go to the Demo to view.

This article is prepared by the author Wang Longshuai, reprint please retain the copyright website, thank you for your understanding and sharing, let life become better!