Search code examples
swiftuikit

How to add image between text in swift?


I have a string with a lot of text and I want to add a picture between this text. The SwiftUI methods don't work for me. Is it possible to do this in UIKit? I want the text and pictures to be on the same line (string or something else). The main thing is that it can be transferred to the label!

This is what I want the string to look like:

enter image description here

I tried this, but it gives an error

let article = "Start " + String(UIImage(named: "image")) + "End"

Solution

  • Here is the answer to my question

       // function to add an image
        func settingsForImage(image: String) -> NSAttributedString {
            let imageAttachment = NSTextAttachment()
            imageAttachment.image = UIImage(named: image)
            // image size
            imageAttachment.bounds = CGRect(x: 0, y: 0, width: 400, height: 200)
            let imageString = NSAttributedString(attachment: imageAttachment)
            return imageString
        }
        
        let textStart = "Start \n \n"
        let image = settingsForImage(image: "your_image")
        let textEnd = "\n \n End"
        let image1 = settingsForImage(image: "your_image")
        
        let attributedString = NSMutableAttributedString(string: textStart)
        attributedString.append(image)
        attributedString.append(NSMutableAttributedString(string: textEnd))
        attributedString.append(image1)
    
        textLabel.attributedText = attributedString