4m1r
4m1r

Reputation: 12542

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

Upvotes: 4

Views: 4541

Answers (3)

Srinivasan N
Srinivasan N

Reputation: 611

All you can do is, add the required spaces(or whitespace characters) before the source string and then add it to your NSMutableAttributedString.

 NSString *newString = [NSString stringWithFormat:@"  %@", jm.issn] <- Have given two spaces here.

Thanks

Upvotes: 0

rebello95
rebello95

Reputation: 8576

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

Upvotes: 2

jrturton
jrturton

Reputation: 119242

You can't. If you're concatenating attributed strings then there is no "margin" around a specific range in the final string. How would that work with multiple lines or text wrapping?

If you want clear space within an attributed string, use white space characters - spaces or tabs. You can define the position of tab stops using paragraph styles.

Upvotes: 2

Related Questions