Spacing around NSTextAttachment

5.5k views Asked by At

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

5

There are 5 answers

1
Jason On

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)
    }
}
0
simeon On

The above answers no longer worked for me under iOS 15. So I ended up creating and adding an empty "padding" attachment in between the image attachment and attributed text

let padding = NSTextAttachment()
//Use a height of 0 and width of the padding you want
padding.bounds = CGRect(width: 5, height: 0) 
            
let attachment = NSTextAttachment(image: image)
let attachString = NSAttributedString(attachment: attachment)

//Insert the padding at the front
myAttributedString.insert(NSAttributedString(attachment: padding), at: 0)

//Insert the image before the padding
myAttributedString.insert(attachString, at: 0)
0
hstdt On

Add spacing to image(For iOS 15).

extension UIImage {
    func imageWithSpacing(insets: UIEdgeInsets) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(
            CGSize(width: self.size.width + insets.left + insets.right,
                   height: self.size.height + insets.top + insets.bottom), false, self.scale)
        UIGraphicsGetCurrentContext()
        let origin = CGPoint(x: insets.left, y: insets.top)
        self.draw(at: origin)
        let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return imageWithInsets
    }
}
0
coco On

This extension makes it easy to add the space you need. It also works on iOS 16.

extension NSMutableAttributedString {
     func appendSpace(_ width: Double) {
         let space = NSTextAttachment()
         space.bounds = CGRect(x:0, y: 0, width: width, height: 0)
         append(NSAttributedString(attachment: space))
    }
}

// usages
let example = NSMutableAttributedString()
example.appendSpace(42)
...
0
ZkTsin On
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...