If I understand your goal, and how you currently have it implemented. You should check if you need to return first.
if ((cursorPosition.x + 30) >= message.frame.width) {
message.text = message.text.stringByAppendingString("
");
}
Then you should get the now current cursor position, and add your UIImageView there.
let size = CGSize(width: 30, height: 30);
let img = UIImage(named: change_arr[indexPath.row]);
let addImg = UIImageView(image: UIImage(named: change_arr[indexPath.row]));
addImg.frame = CGRect(origin: newCursorPosition, size: size);
message.addSubview(addImg);
then if you need to add spaces, add them now.
As stated in the previous comments using NSTextAttachment will simplify all of this, and prevent you from having to create UIViews, etc...
it would look something like this, and you don't need to check for the cursor position, because it will handle that just like it does with text.
//create your UIImage
let image = UIImage(named: change_arr[indexPath.row]);
//create and NSTextAttachment and add your image to it.
let attachment = NSTextAttachment()
attachment.image = image
//put your NSTextAttachment into and attributedString
let attString = NSAttributedString(attachment: attachment)
//add this attributed string to the current position.
textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
Now the image is inline, and treated like text. If the user backspaces over it, it deletes just like text.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…