NSAttributedString 首行缩进结束

NSAttributedString end of first line indent

我想让 NSAttributedString 的第一行从第一行的右侧缩进 UITextView

因此 NSParagraphStyle 中的 firstLineHeadIndent 将从左起第一行缩进。我想做同样的事情,但是在 UITextView.

的右边

这是我希望文本换行的屏幕截图。

我建议创建 2 个不同的 NSParagraphStyle:一个特定于第一行,第二个特定于文本的其余部分。

    //Creating first Line Paragraph Style
NSMutableParagraphStyle *firstLineStyle = [[NSMutableParagraphStyle alloc] init];
[firstLineStyle setFirstLineHeadIndent:10];
[firstLineStyle setTailIndent:200]; //Note that according to the doc, it's in point, and go from the origin text (left for most case) to the end, it's more a length that a "margin" (from right) that's why I put a "high value"
    //Read there: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/ApplicationKit/Classes/NSMutableParagraphStyle_Class/index.html#//apple_ref/occ/instp/NSMutableParagraphStyle/tailIndent

    //Creating Rest of Text Paragraph Style
NSMutableParagraphStyle *restOfTextStyle = [[NSMutableParagraphStyle alloc] init];
[restOfTextStyle setAlignement:NSTextAlignmentJustified];
//Other settings if needed

    //Creating the NSAttributedString
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:originalString];
[attributedString addAttribute:NSParagraphStyleAttributeName value:firstLineStyle range:rangeOfFirstLine];
[attributedString addAttribute:NSParagraphStyleAttributeName
                         value:restOfTextStyle
                         range:NSMakeRange(rangeOfFirstLine.location+rangeOfFirstLine.length,
                                           [originalString length]-(rangeOfFirstLine.location+rangeOfFirstLine.length))];

    //Setting the NSAttributedString to your UITextView
[yourTextView setAttributedText:attributedString]; 

Text System User Interface Layer Programming Guide中的Setting Text Margins article有这个图:

如您所见,没有 built-in 首行缩进机制。

但是,NSTextContainer 有一个 属性 exclusionPaths,它表示应该从中排除文本的矩形区域的一部分。因此,您可以为 upper-right 角添加一条路径,以防止文本到达那里。

UIBezierPath* path = /* compute path for upper-right portion that you want to exclude */;
NSMutableArray* paths = [textView.textContainer.exclusionPaths mutableCopy];
[paths addObject:path];
textView.textContainer.exclusionPaths = paths;