0

我在文本视图中得到了一个带有图像的属性字符串,属性图像显示正常。问题是每当我添加图像时,它都会替换 textview 中的文本。我想添加属性图像,然后将光标放在图像的末尾,这样我就可以在图像下方添加文本。这是我到目前为止所尝试的,在此先感谢。

    let attachment = NSTextAttachment()
    attachment.image = selectedImage
    let newImageWidth = (textView.bounds.size.width - 10 )
    let scale = newImageWidth/(selectedImage.size.width)
    let newImageHeight = selectedImage.size.height * scale
    attachment.bounds = CGRect(x: 0, y: 0, width: newImageWidth, height: newImageHeight)
    let myAttributedString = NSAttributedString(attachment: attachment)
    textView.textStorage.insert(myAttributedString, at: textView.selectedRange.location)
4

1 回答 1

0

我解决了创建 NSMutableAttributedString() 的问题并添加了一个新的 line 属性以将光标放在图像的底部。希望这对某人有所帮助。

var mutableAttrString = NSMutableAttributedString()

    let attachment = NSTextAttachment()
    attachment.image = selectedImage
    let newImageWidth = (textView.bounds.size.width - 10 )
    let scale = newImageWidth/(selectedImage.size.width)
    let newImageHeight = selectedImage.size.height * scale
    attachment.bounds = CGRect(x: 0, y: 0, width: newImageWidth, height: newImageHeight)
    let myAttributedString = NSAttributedString(attachment: attachment)
    let text:[String:Any] = [NSFontAttributeName:UIFont.boldSystemFont(ofSize: 20)]

   // Fixed my problem of having image replacing text, instead I place the text at the bottom of the image 
    let textAttr = NSMutableAttributedString(string: "bottom of image \n", attributes: text)

    mutableAttrString.append(myAttributedString)
    mutableAttrString.append(textAttr)

    textView.attributedText = mutableAttrString
于 2017-12-22T15:42:03.453 回答