NSTextAttachment周围的间距

15

如何使NSTextAttachments周围有间距,就像下面的示例一样?

在示例中,当我将NSTextAttachment添加到NSAttributedString中时,默认行为是没有间距的。

输入图像说明


添加空格,还是添加NSKernAttributeName?没有默认的空格,就像连续书写两个字母一样,但是这里不是字母,而是图像。 - Larme
我尝试了NSKernAttributeName,但它没有起作用。 - Morten Gustafsson
2
在它们之间添加 NSAttributedString *space = [[NSAttributedString alloc] initWithString: @" "] 吗? - Larme
像上面建议的那样,一个空格并不能提供任何精度,但它可以作为一个快速而丑陋的解决方案。 - Jonny
5个回答

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)

6

这在Swift中对我奏效了。

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

1
嗯,似乎在iOS 15上出了问题。可能是TextKit2的问题。https://dev59.com/8lEG5IYBdhLWcg3wQoNw - Ded77

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...

0

这个扩展使得添加所需的空间变得容易。它还可以在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
在图像中添加间距(适用于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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接