如何对齐UITextView中嵌入的图像

时间:2017-02-28 12:28:02

标签: ios swift

由于我的应用逻辑,我需要在UITextView内提供一些带有图片的文字。嵌入图像不是问题(例如,这里给出了工作解决方案How to add image and text in UITextView in IOS?)。但我完全不知道如何对齐图像。我尝试设置属性

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

但它对图像没有影响。文本对齐良好,但图像始终粘在视图的左边缘。 怎么解决?提前谢谢。

1 个答案:

答案 0 :(得分: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

您可以使用此代码根据需要更改方向和比例。