2017-02-28 3 views
0

Aufgrund meiner App-Logik muss ich einen Text mit Bildern innerhalb von UITextView präsentieren. Es ist kein Problem ein Bild einzubetten (Arbeitslösung ist hier zB How to add image and text in UITextView in IOS?). Aber ich habe absolut keine Ahnung, wie man das Bild ausrichtet. Ich versuche, AttributeAusrichten eines in UITextView eingebetteten Bildes

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 

zu setzen, aber es hat keinen Einfluss auf das Bild. Der Text ist gut ausgerichtet, aber das Bild bleibt immer am linken Rand der Ansicht hängen. Wie es zu beheben? Danke im Voraus.

+0

Wie möchten Sie das Bild zuordnen? –

+0

Ich möchte es in der Mitte der Superview haben –

+0

Überprüfen Sie meine Antwort, könnte es Ihnen helfen. –

Antwort

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 

Mit diesem Code können Sie die Ausrichtung und Skalierung nach Ihren Bedürfnissen ändern.