【问题标题】:Spacing around NSTextAttachmentNSTextAttachment 周围的间距
【发布时间】:2017-05-20 23:24:45
【问题描述】:

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

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

【问题讨论】:

  • 添加空格,还是添加 NSKernAttributeName ?没有默认空格,就像一个接一个地写两个字母,但不是字母而是图像。
  • 我试过 NSKernAttributeName 但没用。
  • 在它们之间添加NSAttributedString *space = [[NSAttributedString alloc] initWithString: @" "]
  • 空格,就像上面建议的那样,没有给出任何精确度,但它确实可以作为一个快速而丑陋的修复。

标签: swift3 uitextview nsattributedstring nstextattachment


【解决方案1】:

这在 Swift 中对我有用

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

【讨论】:

【解决方案2】:

以上答案在 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)

【讨论】:

    【解决方案3】:
    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...
    

    【讨论】:

      【解决方案4】:

      为图像添加间距(适用于 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
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-04-26
        • 2019-05-25
        • 1970-01-01
        • 1970-01-01
        • 2012-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多