带有不同NSMutableParagraphStyle的Nsattributedstring

5

我有一个带有多个段落的属性字符串。
我已经将FirstLineHeadIndent = 2.12.
现在我想在属性字符串中给第一个段落FirstLineHeadIndent=0, 并给第二个段落FirstLineHeadIndent=2

如果我像下面这样设置属性:

 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,
                              };

它将为段落和标题留出一些空间。
请看以下图片以获取更多帮助: enter image description here

1
你是如何将段落样式设置到你的 NSAttributedString 中的? - Larme
@Larme 我已经通过NSMutableParagraphStyle设置了段落样式。但是它会影响所有段落。我想要为第一和第二段设置不同的样式。例如,第一段有2个行间距,第二段有4个行间距。 - ios developer
你能展示所有的代码吗? - Larme
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.firstLineHeadIndent = 2; paragraphStyle.paragraphSpacing = paragraph_space;NSDictionary *ats = @{ NSFontAttributeName : [UIFont fontWithName:self.bookView.defaultFontFamily size:self.bookView.defaultFontSize], NSParagraphStyleAttributeName : paragraphStyle, }; - ios developer
你需要使用两个段落样式,分别应用于不同的范围。你这样做了吗? - Larme
显示剩余3条评论
1个回答

6
因此,解决方案是使用2个段落样式。
您的NSString\n分隔,表示两个段落之间的分隔符。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接