2017-02-28 33 views
0

由於我的應用程序邏輯,我需要在UITextView中提供一些帶有圖像的文本。嵌入圖像並不是問題(例如,可以使用工作解決方案How to add image and text in UITextView in IOS?)。但我絕對不知道如何對齊圖像。我嘗試設置屬性如何對齊嵌入在UITextView中的圖像

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 

但它不影響圖像。文本對齊良好,但圖像始終卡在視圖的左邊緣。 如何解決它?提前致謝。

+0

你想如何對齊圖像? –

+0

我想在超級視圖的中心 –

+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 

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