Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString end of first line indent

I want to have the first line in an NSAttributedString for a UITextView indented from the right side on the first line.

So the firstLineHeadIndent in NSParagraphStyle will indent the first line from the left. I want to do the same thing but from the right in my UITextView.

Here's a screenshot of how I want the text to wrap.
enter image description here

like image 756
Berry Blue Avatar asked Dec 03 '22 18:12

Berry Blue


2 Answers

The Setting Text Margins article from the Text System User Interface Layer Programming Guide has this figure:

enter image description here

As you can see, there's no built-in mechanism to have a first line tail indent.

However, NSTextContainer has a property exclusionPaths which represents parts of its rectangular area from which text should be excluded. So, you could add a path for the upper-right corner to prevent text from going there.

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;
like image 88
Ken Thomases Avatar answered Dec 05 '22 08:12

Ken Thomases


I'd suggest to create 2 different NSParagraphStyle: one specific for the first line and the second one for the rest of the text.

    //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]; 
like image 33
Larme Avatar answered Dec 05 '22 06:12

Larme