2017-08-08 148 views
0

我正在開發一個應用程序,我有一個文本以及UIImageUITextView裏面,我試圖垂直對齊文本以及圖像在水平方向左側,我怎麼能做到這一點?垂直和水平對齊的文本以及UIImage在UITextView內

let image = UIImage(named: "Downward Arrow - 01.png") //Step (10) This is where the image is defined. 

let attachment = NSTextAttachment() // Step (10) inserting a NSTextAttachment in order to attach the image in a UITextView. 

let scaledImage = image?.scaleImageToSize(img: image!, size: CGSize(width: 30, height: 30)) // this line of code is needed in order to resize the size of the image. 

attachment.image = scaledImage // Step (10) setting the image to be attached to the scaled one that we just obtained out of the previous code. 

//put your NSTextAttachment into and attributedString 

let attString = NSAttributedString(attachment: attachment) // Step (10). 

testTextView.textStorage.insert(attString, at: testTextView.selectedRange.location) // Step (10). 
+0

您是否使用'UITextField'或'UITextView'? – GIJOW

+0

我正在使用UITextView –

回答

0

你可以有這樣的事情使用邊緣插圖

let image = UIImage(named: "Downward Arrow - 01.png") //Step (10) This is where the image is defined. 

let attachment = NSTextAttachment() // Step (10) inserting a NSTextAttachment in order to attach the image in a UITextView. 

let scaledImage = image?.scaleImageToSize(img: image!, size: CGSize(width: 30, height: 30)) // this line of code is needed in order to resize the size of the image. 

let vCenter = ((testTextView.frame.size.height - 30)/2) 
let padding = UIEdgeInsets(top: vCenter, left: 0, bottom: 0, right: 0) 
testTextView.textContainerInset = padding 

attachment.image = scaledImage // Step (10) setting the image to be attached to the scaled one that we just obtained out of the previous code. 

//put your NSTextAttachment into and attributedString 

let pic = NSAttributedString(attachment: attachment) // Step (10). 
let text = NSAttributedString(string: "YOUR TEXT") 
let attString = NSMutableAttributedString() 
attString.append(pic) 
attString.append(text) 

testTextView.textStorage.insert(attString, at: testTextView.selectedRange.location) // Step (10). 

結果: enter image description here

+0

感謝GIJOW的快速回復,這對於解決我的問題以及在UITextView Vertically中對齊UIImage非常有幫助。然而,我正在尋找的是讓我們說,我有以下幾點:let testText =「你好,你好嗎」然後我的問題是我如何將此文本添加到UITextView內的附加的UIImage,然後垂直對齊,在同時將文本對齊到左邊,圖像對齊?非常感謝! –

+0

抱歉無法理解 – GIJOW

+0

讓textInsideTextView =「Hello world」;讓圖像= UIImage(命名爲:「向下箭頭 - 01.png」)/ /步驟(10)這是圖像定義的地方。 let attachment = NSTextAttachment()//步驟(10)插入NSTextAttachment以將圖像附加到UITextView中。 let scaledImage = image?.scaleImageToSize(img:image !, size:CGSize(width:30,height:30))//這行代碼是調整圖像大小所必需的。 attachment.image = scaledImage //步驟(10)將圖像附加到我們剛剛從前面的代碼中獲取的縮放後的圖像上。 –