NSAttributedString end of first line indent

前端 未结 2 1915
梦谈多话
梦谈多话 2021-02-10 21:50

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

So the firstLineH

2条回答
  •  有刺的猬
    2021-02-10 22:40

    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]; 
    

提交回复
热议问题