Nsattributedstring with different NSMutableParagraphStyle

六眼飞鱼酱① 提交于 2021-02-06 13:54:10

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/23650373/nsattributedstring-with-different-nsmutableparagraphstyle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!