Rasputin
Rasputin

Reputation: 21

How can I insert image to end of the string and insert more than one image in UITextView with swift?

I created an UITextView and I can add image with image picker into text view. But I have some problem about replacement image. I want add this image end of the text. And I want to add images more than one. (like: text + image + text...). How can I solve this problem ? Can anyone help me ?

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
}()

Upvotes: 0

Views: 443

Answers (1)

David Chopin
David Chopin

Reputation: 3064

What you should do is use UITextView's textContainer's exclusionPaths property. The exclusionPaths property lets you assign an array of UIBezierPaths to your textContainer. When exclusionPaths are set, none of the UITextView's text will appear within these paths. You could then add a UIImageView as a subview of the UITextView's super view placed above the UITextView that has a frame equal to said exclusion path.

The end result will be a UITextView with a UIImageView placed above it. None of the UITextView's text will be blocked by the UIImageView as the UITextView's textContainer's exclusionPaths have instructed the text not to populate there.

enter image description here

Here is an example of some code I've done to do something similar, with variable names changed to match your code a bit:

let imageView: UIImageView!

func addImageView() {
    imageView = UIImageView(frame: CGRect(x: textView.frame.maxX - 200, y: textView.frame.maxY - 150, width: 200, height: 150))
    textView.superView.addSubview(imageView)
}

func setExclusionPath(for imageView: UIImageView) {
    let imageViewPath = UIBezierPath(rect: CGRect(x: textView.frame.maxX - imageView.frame.width, y: textView.frame.maxY - imageView.frame.height, width: imageView.frame.width, height: imageView.frame.height))
    textView.textContainer.exclusionPaths.append(imageViewPath)
}

func someMethod() {
    addImageView()
    setExclusionPath(for: self.imageView)
}

Resources: exclusionPaths reference from Apple

Upvotes: 1

Related Questions