【问题标题】:How to add images as text attachment in Swift using NSAttributedString?如何使用 NSAttributedString 在 Swift 中添加图像作为文本附件?
【发布时间】:2015-12-22 16:27:24
【问题描述】:

我正在尝试使用我作为按钮放入的图像为 iOS 构建自定义键盘。当我按下一个按钮时,链接到该按钮的图像被放入一个属性字符串中,该字符串被加载到自定义键盘视图内的 UiTextView 中。这是有效的。

问题在于,当我将新图像附加到属性字符串时,字符串中的旧图像和新图像都会更改为我当前按下的图像。我不明白为什么字符串中的旧图像会发生变化。

有什么建议吗?我尝试过使用replaceCharactersInRange 和insertAttributedString,但无法正常工作。这是代码(在 viewDidLoad 之后):

let textAttachment = NSTextAttachment()

let textView = UITextView(frame: CGRectMake(5, 5, 200, 40))
var attributedString = NSMutableAttributedString(string: "")
    
@IBAction func buttonPressed(button :UIButton) {
          
    let string = button.titleLabel?.text
    
    textAttachment.image = UIImage(named: "\(string!).png")!
    textAttachment.image = UIImage(CGImage: textAttachment.image!.CGImage!, scale: 6, orientation: .Up)
    let attrStringWithImage = NSAttributedString(attachment: textAttachment)
    attributedString.appendAttributedString(attrStringWithImage);
    
    textView.attributedText = attributedString;
}

【问题讨论】:

  • 您为每个图像重复使用相同的textAttachment,这是您的问题。每次只需创建一个新的NSTextAttachment(),无需存储。

标签: ios iphone swift ios-app-extension custom-keyboard


【解决方案1】:

我们不能简单地附加 NSTextAttachment 图片。我们必须存储 所有附加的图像和连接到现有的属性 字符串。

func buttonPressed(_ sender: Any) {

    let  button = sender as! UIButton
    let tag =  button.tag
    let attributedString:NSAttributedString!

    switch tag {
    case 2:
        attributedString = addAttributedText(text: (button.titleLabel?.text)!)
    case 3:
        attributedString = addAttributedText(text: (button.titleLabel?.text)!)
    case 4:
        attributedString = addAttributedText(text: (button.titleLabel?.text)!)
    default:
       attributedString = addAttributedText(text: "launch")
      }
        textView.attributedText = attributedString
    }

    func addAttributedText(text:String) -> NSAttributedString {
        textViewDidChange(textView)
        let axtractedImageAttribute = NSMutableAttributedString()
        for image in imageArray {
            let attachment:NSTextAttachment = NSTextAttachment()
            attachment.image = image
            attachment.setImageHeight(height: 20)
            let attachmentString:NSAttributedString = NSAttributedString(attachment: attachment)
            axtractedImageAttribute.append(attachmentString)
        }

        let attachment:NSTextAttachment = NSTextAttachment()
        attachment.image = UIImage(named: "\(text).png")
        attachment.setImageHeight(height: 20)
        let attachmentString:NSAttributedString = NSAttributedString(attachment: attachment)
        let attributedString:NSMutableAttributedString = NSMutableAttributedString(string:textView.text!)
        attributedString.append(axtractedImageAttribute)
        attributedString.append(attachmentString)
        return attributedString
    }

    //MARKS:-  Extract attachedImage
    func textViewDidChange(_ textView: UITextView)  {
        imageArray = [UIImage]()
        let range = NSRange(location: 0, length: textView.attributedText.length)
        if (textView.textStorage.containsAttachments(in: range)) {
            let attrString = textView.attributedText
            var location = 0
            while location < range.length {
                var r = NSRange()
                let attrDictionary = attrString?.attributes(at: location, effectiveRange: &r)
                if attrDictionary != nil {
                    let attachment = attrDictionary![NSAttachmentAttributeName] as? NSTextAttachment
                    if attachment != nil {
                        if attachment!.image != nil {
                            imageArray.append( attachment!.image!)
                        }
                    }
                    location += r.length
                }
            }
        }
    }

}

Demo Reference

【讨论】:

  • 如果我附有 2 张不同的图片,我如何识别我点击的是哪一张?单击图像附件时,我确实编写了代码以打印某些内容,但是我需要根据图像实现不同的操作。
  • 另外,可以附上视频吗?
  • 如何为这个附加到字符串的图像提供操作?
  • @Shrawan “一些文字”+图片+“又是一些文字”+图片
【解决方案2】:

这是我的扩展 Swift 4,将图像更改为属性字符串,并改变大小和色调

public extension UIImage {

    func tint(with color: UIColor) -> UIImage {
        var image = withRenderingMode(.alwaysTemplate)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        color.set()

        image.draw(in: CGRect(origin: .zero, size: size))
        image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }

    func toAttributedString(with heightRatio: CGFloat, tint color: UIColor? = nil) -> NSAttributedString {
        let attachment = NSTextAttachment()
        var image = self

        if let tintColor = color {
            image.withRenderingMode(.alwaysTemplate)
            image = image.tint(with: tintColor)
        }

        attachment.image = image

        let ratio: CGFloat = image.size.width / image.size.height
        let attachmentBounds = attachment.bounds

        attachment.bounds = CGRect(x: attachmentBounds.origin.x,
                                   y: attachmentBounds.origin.y,
                                   width: ratio * heightRatio,
                                   height: heightRatio)

        return NSAttributedString(attachment: attachment)
    }
}

【讨论】:

    【解决方案3】:

    我发现了问题,我需要为 NSTextAttachment 设置不同的变量(即 textAttachment1、textAttachment2 等),否则它只会使用已解决的第一个图像。

    【讨论】:

      【解决方案4】:

      这对我有用:

      let attributedStringTextAttachment = NSTextAttachment()
      attributedStringTextAttachment.image = UIImage(named: "image")
      

      【讨论】:

        猜你喜欢
        • 2015-05-08
        • 1970-01-01
        • 2013-06-07
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多