归属字符串图像替换UItextview中的文本

时间:2017-12-22 14:20:51

标签: swift3 uitextview nsattributedstring nstextattachment

我在textview中得到了一个带有图像的属性字符串,属性图像显示正常。问题是每当我添加图像时它都会替换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)

1 个答案:

答案 0 :(得分: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
相关问题