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 photos of attachments 2 attachment.image = UIImage (picture name ) 3 // Set the size of the attachment (-4 This number can be adjusted according to the actual situation, the width of the height can also set their own, where the font size for reference) 4 attachment.bounds = CGRectMake (0 ,-4 5 Converts an attachment to the attributed text of the nsattributedstring type 6 let Attstr = nsattributedstring (Attac hment: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 // gets all the text of the TextView and turns it into a 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+10)
"Swift" text mix, insert picture in iOS development in TextField or TextView