NSTextAttachment周围的间距

Mor*_*son 7 uitextview nsattributedstring nstextattachment swift3

如何在NSTextAttachments周围设置间距,如下例所示?

在示例中,无间距是我将NSTextAttachment附加到NSAttributedString时的默认行为.

在此输入图像描述

sim*_*eon 7

上面的答案在 iOS 15 下不再适用于我。所以我最终在图像附件和属性文本之间创建并添加了一个空的“填充”附件

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)
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 5

这在 Swift 中对我有用

public extension NSMutableAttributedString {    
    func appendSpacing( points : Float ){
        // zeroWidthSpace is 200B
        let spacing = NSAttributedString(string: "\u{200B}", attributes:[ NSAttributedString.Key.kern: points])
        append(spacing)
    }
}
Run Code Online (Sandbox Code Playgroud)


ZkT*_*sin 1

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...
Run Code Online (Sandbox Code Playgroud)