Search code examples
iosobjective-cnsattributedstring

What's the best way to add a left margin to an NSAttributedString?


I'm trying to add a left hand margin to an NSAttributedString so that when I concatenate it with another NSAS, there is a bit of space between the two box frames.

All I have so far is this:

NSMutableAttributedString *issn = [[NSMutableAttributedString alloc] initWithString:jm.issn attributes:nil];

NSRange range = NSMakeRange(0, [issn length]);
[issn addAttribute:NSFontAttributeName
             value:[UIFont fontWithName:@"AvenirNext-Medium" size:8]
             range:range];

NSMutableAttributedString *textLabel = [[NSMutableAttributedString alloc] initWithAttributedString:title];
[textLabel  appendAttributedString:issn];

I want the margin on the left side of the second string.

Thanks!

Edit: image upload

enter image description here


Solution

  • Why not just use a tab character between the two strings?

    You could do this by changing your first line to this:

    NSMutableAttributedString *issn = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"\t%@", jm.issn] attributes:nil];
    

    This should output something like like what you want. You may, however, want to add 2 \t characters instead of one because depending on the string length, it may not need a tab character to align it (for example, in that exact string you posted, it didn't add anything to my output).

    1 tab with your string:

    One tab

    2 tabs with your string:

    Two tabs