如何在字符串末尾插入图像并快速在UITextView中插入多个图像?

时间:2019-09-09 20:04:11

标签: swift uiimageview uitextview nsattributedstring nstextattachment

我创建了一个UITextView,并且可以将带有图像选择器的图像添加到文本视图中。但是我有一些关于替换图像的问题。我要将此图像添加到文本末尾。我想添加多个图像。 (例如:文字+图片+文字...)。我怎么解决这个问题 ?谁能帮我吗?

let pickImage = UIImageView() // this is for imagepickercontroller 

lazy var writePost: UITextView = {
    let wpost = UITextView()

    let images = pickImage
    let attachment = NSTextAttachment()
    let attString = NSAttributedString(attachment: attachment)
    attachment.image = images.image
    images.frame = CGRect(x: 0, y: 0, width: 220, height: 220)
    images.contentMode = .scaleAspectFill
    wpost.textStorage.insert(attString, at: wpost.selectedRange.location)
    wpost.addSubview(images)

    wpost.textAlignment = .center
    wpost.textColor = UIColor.lightGray
    wpost.font = UIFont(name: "AvenirNext-DemiBoldItalic", size: 16)

    wpost.isEditable = true
    wpost.isScrollEnabled = true
    wpost.layer.borderWidth = 1.5
    wpost.layer.cornerRadius = 7.0
    wpost.layer.borderColor = UIColor.orange.cgColor

    wpost.delegate = self

    return wpost
}()

1 个答案:

答案 0 :(得分:1)

您应该做的是使用UITextView的{​​{1}}的{​​{1}}属性。 textContainer属性使您可以将exclusionPaths的数组分配给exclusionPaths。设置UIBezierPath后,textContainer的文本将不会出现在这些路径中。然后,您可以添加exclusionPaths作为UITextView的超级视图的子视图,该子视图位于UIImageView上方,其框架等于所述排除路径。

最终结果将是UITextView,上方放置UITextViewUITextView的文本不会被UIImageView阻塞,因为UITextView的{​​{1}}的{​​{1}}指示文本不要在此处填充

enter image description here

以下是我为执行类似操作而编写的一些代码示例,其中变量名称已更改为与您的代码有点匹配:

UIImageView

资源: exclusionPaths reference from Apple