11

How do I make spacing around NSTextAttachments like in the example below?

In the example No spacing is the default behaviour I get when I append a NSTextAttachment to a NSAttributedString.

enter image description here

Morten Gustafsson
  • 1,719
  • 2
  • 21
  • 34
  • Add white spaces, or add NSKernAttributeName ? There is no default space, it's like writing two letters one after the other, but instead of letter it's images. – Larme Jan 06 '17 at 09:33
  • I tried NSKernAttributeName but it didn't work. – Morten Gustafsson Jan 06 '17 at 09:41
  • 2
    Add `NSAttributedString *space = [[NSAttributedString alloc] initWithString: @" "]` between each of them? – Larme Jan 06 '17 at 15:05
  • A space, like suggested above, doesn't give any precision, but it does work as a quick and ugly fix. – Jonny Mar 01 '18 at 10:59

2 Answers2

4

This worked for me in Swift

public extension NSMutableAttributedString {    
    func appendSpacing( points : Float ){
        // zeroWidthSpace is 200B
        let spacing = NSAttributedString(string: "\u{200B}", attributes:[ NSAttributedString.Key.kern: points])
        append(spacing)
    }
}
Jason
  • 1,144
  • 10
  • 16
0
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
// append NSTextAttachments instance to attributedText...
// then add non-printable string with NSKernAttributeName attributes
unichar c[] = { NSAttachmentCharacter };
NSString *nonprintableString = [NSString stringWithCharacters:c length:1];
NSAttributedString *spacing = [[NSAttributedString alloc] initWithString:nonprintableString attributes:@{
    NSKernAttributeName : @(4) // spacing in points
}];
[attributedText appendAttributedString:spacing];

// finally add other text...
ZkTsin
  • 1
  • 1