Search code examples
iosattributesnsattributedstring

Nsattributedstring with different NSMutableParagraphStyle


I have 1 attributed string with multiple paragraph.
I had given the FirstLineHeadIndent = 2.12.
Now I want to give the FirstLineHeadIndent=0 to 1st paragraph and FirstLineHeadIndent=2 to 2nd paragraph in the attributed string.

If I set the property like

 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing =Line_space;
        paragraphStyle.firstLineHeadIndent =2;
        paragraphStyle.headIndent =margin_space;
        paragraphStyle.tailIndent =-margin_space;
        paragraphStyle.paragraphSpacing=paragraph_space;

        NSDictionary *ats = @{
                              NSFontAttributeName : [UIFont fontWithName:self.bookView.defaultFontFamily size:self.bookView.defaultFontSize],
                              NSParagraphStyleAttributeName : paragraphStyle,
                              };

It will give the head space to both the paragaraph. Please help me. I am uploading the image for more help:- enter image description here


Solution

  • So, the solution is to use 2 paragraph styles.
    Your NSString is separated by a \n, that indicate the separations between the 2 paragraphs.

    NSMutableParagraphStyle *firstParagraphStyle = [[NSMutableParagraphStyle alloc] init];
    [firstParagraphStyle setFirstLineHeadIndent:0];
    //Do the rest of the settings
    
    NSMutableParagraphStyle *secondParagraphStyle = [[NSMutableParagraphStyle alloc] init];
    [secondParagraphStyle setFirstLineHeadIndent:2];
    //Do the rest of the settings
    
    //You may use the same paragraphStyle, changing just the firstLineHeadIndent, and set the attributes, but for a clearer explanation, I used 2 paragraph styles
    NSRange range = [[yourAttributedString string] rangeOfString:@"\n"];
    
    [yourAttributedString addAttribute:NSParagraphStyleAttributeName value: firstParagraphStyle range:NSMakeRange(0, range.location)]; //The range is from the start to the \n
    
    [yourAttributedString addAttribute:NSParagraphStyleAttributeName value: secondParagraphStyle range:NSMakeRange(range.location, [[yourAttributedString string] length]-range.location)]; //The range is from the start of \n to the end