How to format a string to display correctly in ios

I have a FAQ section in my application, but I have to present it in a specific way using a non-editable UITextView. As below,

  • How can I cancel my appointment?

    and. You can cancel the recording while it is in progress by pressing the cancel button (red "X")

      in the center of the speaker on the recording screen. The audio recording 
      will not be saved. 
    
          

But the problem is that you can see that it should be displayed with some padding, and the next line should start just below the "not below A" response line . And there is a huge question doc so I can't format it manually. And this is for iPhone and iPad, so the width of the UITextView is different. Is there any solution to this problem?

+3


source to share


1 answer


I would suggest using NSAttributedString

and NSParagraphStyle

in combination with NSParagraphAttributeName

.

Here's an example:



NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:yourString];

int indent1 = 0;
int indent2 = 20;
int indent3 = 2*indent2;

NSMutableParagraphStyle *styleTitleByNumber = [[NSMutableParagraphStyle alloc] init];
[styleTitleByNumber setFirstLineHeadIndent:indent1];
[styleTitleByNumber setHeadIndent:indent1];

NSMutableParagraphStyle *styleTitleByLetter = [[NSMutableParagraphStyle alloc] init];
[styleTitleByLetter setFirstLineHeadIndent:indent2];
[styleTitleByLetter setHeadIndent:indent2];

NSMutableParagraphStyle *styleSimpleText = [[NSMutableParagraphStyle alloc] init];
[styleSimpleText setFirstLineHeadIndent:indent3];
[styleSimpleText setHeadIndent:indent3];

[attributedString addAttribute:NSParagraphStyleAttributeName 
                         value:styleTitleByNumber
                         range:rangeOfTitleByNumber];
[attributedString addAttribute:NSParagraphStyleAttributeName 
                          value:styleTitleByLetter 
                          range:rangeOfTitleByLetter];
[attributedString addAttribute:NSParagraphStyleAttributeName 
                          value:styleSimpleText
                          range:rangeOfSimpleText];

[yourTextView setAttributedText:attributedString];

      

Now, depending on how your original text is formatted, I leave it up to you to know where to apply this style (for the parameter NSRange

), or you can also, if the different parts are separated, apply direct influence on NSAttributedString

and then merge them all.

+2


source







All Articles