Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spacing around NSTextAttachment

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

like image 757
Morten Gustafsson Avatar asked Jan 06 '17 08:01

Morten Gustafsson


3 Answers

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)
like image 57
simeon Avatar answered Nov 10 '22 06:11

simeon


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)
    }
}
like image 35
Jason Avatar answered Nov 10 '22 05:11

Jason


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...
like image 1
ZkTsin Avatar answered Nov 10 '22 06:11

ZkTsin