In iOS development, we typically enter text in TextField or TextView. When we need to insert a picture, it's actually very simple.We need to take advantage of the attributed text of the Textfield,textview, insert the picture as an attachment
The steps are as follows: (in TextView, the same in OC)
- Create attachments while setting the font size of TextView (or set in storyboard)
1 //Set font 2 Textview.font = uifont.systemfontofsize 3 //Create Attachment 4 let attachment = Nstextattachment ()
-
Set the Picture property of the attachment to the picture you want to insert, convert the attachment to attributed text, and set the size of the attachment
-
1 //Set attachment photo 2 attachment.image = UIImage (picture name) 3 //Set Attachment size (-4 This number can be adjusted according to the actual situation, the width of the height can also set their own, here with the font size for reference) 4 attachment.bounds = CGRectMake (0, -4, TextView.font.lineHeight, textView.font.lineHeight) 5 // Convert an attachment to an attributed text of type nsattributedstring 6 let attstr = nsattributedstring (attachment:attachment)
- Gets the text in the current TextView, turns it into a variable text, records the position of the cursor, and inserts the attributed text in the previous step
-
1 //Get all the text of TextView, turn it into variable text 2 var mutablestr = nsmutableattributedstring (attributedstring: Textview.attributedtext) 3 //Get the current cursor position 4 let selectedrange = textview.selectedrange5 //Insert text 6 Mutablestr.insertattributedstring (Attstr, atIndex:selectedRange.location)
- Sets the properties of the new variable text and calculates the new cursor position
-
1 //Set font properties for variable text 2 mutablestr.addattribute (Nsfontattributename, value:UIFont.systemFontOfSize), range : Nsmakerange (0,mutablestr.length)) 3 //Remember again the position of the new Cursor 4 let newselectedrange = Nsmakerange ( selectedrange.location+1, 0)
"Swift" text mix, insert picture in iOS development in TextField or TextView