0

Because of my app logic I need to present some text with images within UITextView. It's not a problem to embed an image (working solution is given, for example, here How to add image and text in UITextView in IOS?). But I absolutely have no clue how to align the image. I try to set attributes

var attributedString: NSMutableAttributedString!
let textAttachment = NSTextAttachment()
let image = UIImage(named: imageName)            

textAttachment.image = image
let attrStringWithImage = NSAttributedString(attachment: textAttachment)

let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.justified
let attrs = [NSParagraphStyleAttributeName: style]

attributedString = NSMutableAttributedString(attributedString: attrStringWithImage)
let text = NSAttributedString(string: myText, attributes: attrs)
attributedString.append(text)

myTextView?.attributedText = attributedString

but it doesn't influence on image. The text is aligned good, but the image always get stuck to the left edge of the view. How to fix it? Thanks in advance.

Community
  • 1
  • 1

1 Answers1

0
var attributedString: NSMutableAttributedString!
    let textAttachment = NSTextAttachment()
    let image = UIImage(named: yourImage)

    textAttachment.image = image

    textAttachment.image = UIImage(cgImage: (textAttachment.image?.cgImage)!, scale: 20, orientation: UIImageOrientation.left)
    let attrStringWithImage = NSAttributedString(attachment: textAttachment)

    let style = NSMutableParagraphStyle()
    style.alignment = NSTextAlignment.justified
    let attrs = [NSParagraphStyleAttributeName: style]

    attributedString = NSMutableAttributedString(attributedString: attrStringWithImage)
    let text = NSAttributedString(string: yourText, attributes: attrs)
    attributedString.append(text)

    txtView?.attributedText = attributedString

You can change orientation and scale as per your need using this code.

Punit
  • 1,330
  • 6
  • 13